PackageManagerService.java revision db4a79a5d7d348e9d2286d95d4e5a59dd484456f
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.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
71import static android.content.pm.PackageManager.PERMISSION_DENIED;
72import static android.content.pm.PackageManager.PERMISSION_GRANTED;
73import static android.content.pm.PackageParser.isApkFile;
74import static android.os.Process.PACKAGE_INFO_GID;
75import static android.os.Process.SYSTEM_UID;
76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
77import static android.system.OsConstants.O_CREAT;
78import static android.system.OsConstants.O_RDWR;
79
80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
84import static com.android.internal.util.ArrayUtils.appendInt;
85import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
94
95import android.Manifest;
96import android.annotation.NonNull;
97import android.annotation.Nullable;
98import android.app.ActivityManager;
99import android.app.ActivityManagerNative;
100import android.app.AppGlobals;
101import android.app.IActivityManager;
102import android.app.admin.IDevicePolicyManager;
103import android.app.backup.IBackupManager;
104import android.content.BroadcastReceiver;
105import android.content.ComponentName;
106import android.content.Context;
107import android.content.IIntentReceiver;
108import android.content.Intent;
109import android.content.IntentFilter;
110import android.content.IntentSender;
111import android.content.IntentSender.SendIntentException;
112import android.content.ServiceConnection;
113import android.content.pm.ActivityInfo;
114import android.content.pm.ApplicationInfo;
115import android.content.pm.AppsQueryHelper;
116import android.content.pm.ComponentInfo;
117import android.content.pm.EphemeralApplicationInfo;
118import android.content.pm.EphemeralResolveInfo;
119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
120import android.content.pm.FeatureInfo;
121import android.content.pm.IOnPermissionsChangeListener;
122import android.content.pm.IPackageDataObserver;
123import android.content.pm.IPackageDeleteObserver;
124import android.content.pm.IPackageDeleteObserver2;
125import android.content.pm.IPackageInstallObserver2;
126import android.content.pm.IPackageInstaller;
127import android.content.pm.IPackageManager;
128import android.content.pm.IPackageMoveObserver;
129import android.content.pm.IPackageStatsObserver;
130import android.content.pm.InstrumentationInfo;
131import android.content.pm.IntentFilterVerificationInfo;
132import android.content.pm.KeySet;
133import android.content.pm.PackageCleanItem;
134import android.content.pm.PackageInfo;
135import android.content.pm.PackageInfoLite;
136import android.content.pm.PackageInstaller;
137import android.content.pm.PackageManager;
138import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
139import android.content.pm.PackageManagerInternal;
140import android.content.pm.PackageParser;
141import android.content.pm.PackageParser.ActivityIntentInfo;
142import android.content.pm.PackageParser.PackageLite;
143import android.content.pm.PackageParser.PackageParserException;
144import android.content.pm.PackageStats;
145import android.content.pm.PackageUserState;
146import android.content.pm.ParceledListSlice;
147import android.content.pm.PermissionGroupInfo;
148import android.content.pm.PermissionInfo;
149import android.content.pm.ProviderInfo;
150import android.content.pm.ResolveInfo;
151import android.content.pm.ServiceInfo;
152import android.content.pm.Signature;
153import android.content.pm.UserInfo;
154import android.content.pm.VerificationParams;
155import android.content.pm.VerifierDeviceIdentity;
156import android.content.pm.VerifierInfo;
157import android.content.res.Resources;
158import android.graphics.Bitmap;
159import android.hardware.display.DisplayManager;
160import android.net.Uri;
161import android.os.Binder;
162import android.os.Build;
163import android.os.Bundle;
164import android.os.Debug;
165import android.os.Environment;
166import android.os.Environment.UserEnvironment;
167import android.os.FileUtils;
168import android.os.Handler;
169import android.os.IBinder;
170import android.os.Looper;
171import android.os.Message;
172import android.os.Parcel;
173import android.os.ParcelFileDescriptor;
174import android.os.Process;
175import android.os.RemoteCallbackList;
176import android.os.RemoteException;
177import android.os.ResultReceiver;
178import android.os.SELinux;
179import android.os.ServiceManager;
180import android.os.SystemClock;
181import android.os.SystemProperties;
182import android.os.Trace;
183import android.os.UserHandle;
184import android.os.UserManager;
185import android.os.storage.IMountService;
186import android.os.storage.MountServiceInternal;
187import android.os.storage.StorageEventListener;
188import android.os.storage.StorageManager;
189import android.os.storage.VolumeInfo;
190import android.os.storage.VolumeRecord;
191import android.security.KeyStore;
192import android.security.SystemKeyStore;
193import android.system.ErrnoException;
194import android.system.Os;
195import android.system.StructStat;
196import android.text.TextUtils;
197import android.text.format.DateUtils;
198import android.util.ArrayMap;
199import android.util.ArraySet;
200import android.util.AtomicFile;
201import android.util.DisplayMetrics;
202import android.util.EventLog;
203import android.util.ExceptionUtils;
204import android.util.Log;
205import android.util.LogPrinter;
206import android.util.MathUtils;
207import android.util.PrintStreamPrinter;
208import android.util.Slog;
209import android.util.SparseArray;
210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
212import android.util.Xml;
213import android.view.Display;
214
215import com.android.internal.R;
216import com.android.internal.annotations.GuardedBy;
217import com.android.internal.app.IMediaContainerService;
218import com.android.internal.app.ResolverActivity;
219import com.android.internal.content.NativeLibraryHelper;
220import com.android.internal.content.PackageHelper;
221import com.android.internal.os.IParcelFileDescriptorFactory;
222import com.android.internal.os.InstallerConnection.InstallerException;
223import com.android.internal.os.SomeArgs;
224import com.android.internal.os.Zygote;
225import com.android.internal.util.ArrayUtils;
226import com.android.internal.util.FastPrintWriter;
227import com.android.internal.util.FastXmlSerializer;
228import com.android.internal.util.IndentingPrintWriter;
229import com.android.internal.util.Preconditions;
230import com.android.server.EventLogTags;
231import com.android.server.FgThread;
232import com.android.server.IntentResolver;
233import com.android.server.LocalServices;
234import com.android.server.ServiceThread;
235import com.android.server.SystemConfig;
236import com.android.server.Watchdog;
237import com.android.server.pm.PermissionsState.PermissionState;
238import com.android.server.pm.Settings.DatabaseVersion;
239import com.android.server.pm.Settings.VersionInfo;
240import com.android.server.storage.DeviceStorageMonitorInternal;
241
242import dalvik.system.DexFile;
243import dalvik.system.VMRuntime;
244
245import libcore.io.IoUtils;
246import libcore.util.EmptyArray;
247
248import org.xmlpull.v1.XmlPullParser;
249import org.xmlpull.v1.XmlPullParserException;
250import org.xmlpull.v1.XmlSerializer;
251
252import java.io.BufferedInputStream;
253import java.io.BufferedOutputStream;
254import java.io.BufferedReader;
255import java.io.ByteArrayInputStream;
256import java.io.ByteArrayOutputStream;
257import java.io.File;
258import java.io.FileDescriptor;
259import java.io.FileNotFoundException;
260import java.io.FileOutputStream;
261import java.io.FileReader;
262import java.io.FilenameFilter;
263import java.io.IOException;
264import java.io.InputStream;
265import java.io.PrintWriter;
266import java.nio.charset.StandardCharsets;
267import java.security.MessageDigest;
268import java.security.NoSuchAlgorithmException;
269import java.security.PublicKey;
270import java.security.cert.CertificateEncodingException;
271import java.security.cert.CertificateException;
272import java.text.SimpleDateFormat;
273import java.util.ArrayList;
274import java.util.Arrays;
275import java.util.Collection;
276import java.util.Collections;
277import java.util.Comparator;
278import java.util.Date;
279import java.util.Iterator;
280import java.util.List;
281import java.util.Map;
282import java.util.Objects;
283import java.util.Set;
284import java.util.concurrent.CountDownLatch;
285import java.util.concurrent.TimeUnit;
286import java.util.concurrent.atomic.AtomicBoolean;
287import java.util.concurrent.atomic.AtomicInteger;
288import java.util.concurrent.atomic.AtomicLong;
289
290/**
291 * Keep track of all those .apks everywhere.
292 *
293 * This is very central to the platform's security; please run the unit
294 * tests whenever making modifications here:
295 *
296runtest -c android.content.pm.PackageManagerTests frameworks-core
297 *
298 * {@hide}
299 */
300public class PackageManagerService extends IPackageManager.Stub {
301    static final String TAG = "PackageManager";
302    static final boolean DEBUG_SETTINGS = false;
303    static final boolean DEBUG_PREFERRED = false;
304    static final boolean DEBUG_UPGRADE = false;
305    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
306    private static final boolean DEBUG_BACKUP = false;
307    private static final boolean DEBUG_INSTALL = false;
308    private static final boolean DEBUG_REMOVE = false;
309    private static final boolean DEBUG_BROADCASTS = false;
310    private static final boolean DEBUG_SHOW_INFO = false;
311    private static final boolean DEBUG_PACKAGE_INFO = false;
312    private static final boolean DEBUG_INTENT_MATCHING = false;
313    private static final boolean DEBUG_PACKAGE_SCANNING = false;
314    private static final boolean DEBUG_VERIFY = false;
315    private static final boolean DEBUG_DEXOPT = false;
316    private static final boolean DEBUG_ABI_SELECTION = false;
317    private static final boolean DEBUG_EPHEMERAL = false;
318    private static final boolean DEBUG_TRIAGED_MISSING = false;
319
320    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
321
322    private static final boolean DISABLE_EPHEMERAL_APPS = true;
323
324    private static final int RADIO_UID = Process.PHONE_UID;
325    private static final int LOG_UID = Process.LOG_UID;
326    private static final int NFC_UID = Process.NFC_UID;
327    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
328    private static final int SHELL_UID = Process.SHELL_UID;
329
330    // Cap the size of permission trees that 3rd party apps can define
331    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
332
333    // Suffix used during package installation when copying/moving
334    // package apks to install directory.
335    private static final String INSTALL_PACKAGE_SUFFIX = "-";
336
337    static final int SCAN_NO_DEX = 1<<1;
338    static final int SCAN_FORCE_DEX = 1<<2;
339    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
340    static final int SCAN_NEW_INSTALL = 1<<4;
341    static final int SCAN_NO_PATHS = 1<<5;
342    static final int SCAN_UPDATE_TIME = 1<<6;
343    static final int SCAN_DEFER_DEX = 1<<7;
344    static final int SCAN_BOOTING = 1<<8;
345    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
346    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
347    static final int SCAN_REPLACING = 1<<11;
348    static final int SCAN_REQUIRE_KNOWN = 1<<12;
349    static final int SCAN_MOVE = 1<<13;
350    static final int SCAN_INITIAL = 1<<14;
351
352    static final int REMOVE_CHATTY = 1<<16;
353
354    private static final int[] EMPTY_INT_ARRAY = new int[0];
355
356    /**
357     * Timeout (in milliseconds) after which the watchdog should declare that
358     * our handler thread is wedged.  The usual default for such things is one
359     * minute but we sometimes do very lengthy I/O operations on this thread,
360     * such as installing multi-gigabyte applications, so ours needs to be longer.
361     */
362    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
363
364    /**
365     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
366     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
367     * settings entry if available, otherwise we use the hardcoded default.  If it's been
368     * more than this long since the last fstrim, we force one during the boot sequence.
369     *
370     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
371     * one gets run at the next available charging+idle time.  This final mandatory
372     * no-fstrim check kicks in only of the other scheduling criteria is never met.
373     */
374    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
375
376    /**
377     * Whether verification is enabled by default.
378     */
379    private static final boolean DEFAULT_VERIFY_ENABLE = true;
380
381    /**
382     * The default maximum time to wait for the verification agent to return in
383     * milliseconds.
384     */
385    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
386
387    /**
388     * The default response for package verification timeout.
389     *
390     * This can be either PackageManager.VERIFICATION_ALLOW or
391     * PackageManager.VERIFICATION_REJECT.
392     */
393    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
394
395    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
396
397    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
398            DEFAULT_CONTAINER_PACKAGE,
399            "com.android.defcontainer.DefaultContainerService");
400
401    private static final String KILL_APP_REASON_GIDS_CHANGED =
402            "permission grant or revoke changed gids";
403
404    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
405            "permissions revoked";
406
407    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
408
409    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
410
411    /** Permission grant: not grant the permission. */
412    private static final int GRANT_DENIED = 1;
413
414    /** Permission grant: grant the permission as an install permission. */
415    private static final int GRANT_INSTALL = 2;
416
417    /** Permission grant: grant the permission as a runtime one. */
418    private static final int GRANT_RUNTIME = 3;
419
420    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
421    private static final int GRANT_UPGRADE = 4;
422
423    /** Canonical intent used to identify what counts as a "web browser" app */
424    private static final Intent sBrowserIntent;
425    static {
426        sBrowserIntent = new Intent();
427        sBrowserIntent.setAction(Intent.ACTION_VIEW);
428        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
429        sBrowserIntent.setData(Uri.parse("http:"));
430    }
431
432    final ServiceThread mHandlerThread;
433
434    final PackageHandler mHandler;
435
436    /**
437     * Messages for {@link #mHandler} that need to wait for system ready before
438     * being dispatched.
439     */
440    private ArrayList<Message> mPostSystemReadyMessages;
441
442    final int mSdkVersion = Build.VERSION.SDK_INT;
443
444    final Context mContext;
445    final boolean mFactoryTest;
446    final boolean mOnlyCore;
447    final DisplayMetrics mMetrics;
448    final int mDefParseFlags;
449    final String[] mSeparateProcesses;
450    final boolean mIsUpgrade;
451
452    /** The location for ASEC container files on internal storage. */
453    final String mAsecInternalPath;
454
455    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
456    // LOCK HELD.  Can be called with mInstallLock held.
457    @GuardedBy("mInstallLock")
458    final Installer mInstaller;
459
460    /** Directory where installed third-party apps stored */
461    final File mAppInstallDir;
462    final File mEphemeralInstallDir;
463
464    /**
465     * Directory to which applications installed internally have their
466     * 32 bit native libraries copied.
467     */
468    private File mAppLib32InstallDir;
469
470    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
471    // apps.
472    final File mDrmAppPrivateInstallDir;
473
474    // ----------------------------------------------------------------
475
476    // Lock for state used when installing and doing other long running
477    // operations.  Methods that must be called with this lock held have
478    // the suffix "LI".
479    final Object mInstallLock = new Object();
480
481    // ----------------------------------------------------------------
482
483    // Keys are String (package name), values are Package.  This also serves
484    // as the lock for the global state.  Methods that must be called with
485    // this lock held have the prefix "LP".
486    @GuardedBy("mPackages")
487    final ArrayMap<String, PackageParser.Package> mPackages =
488            new ArrayMap<String, PackageParser.Package>();
489
490    // Tracks available target package names -> overlay package paths.
491    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
492        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
493
494    /**
495     * Tracks new system packages [received in an OTA] that we expect to
496     * find updated user-installed versions. Keys are package name, values
497     * are package location.
498     */
499    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
500
501    /**
502     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
503     */
504    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
505    /**
506     * Whether or not system app permissions should be promoted from install to runtime.
507     */
508    boolean mPromoteSystemApps;
509
510    final Settings mSettings;
511    boolean mRestoredSettings;
512
513    // System configuration read by SystemConfig.
514    final int[] mGlobalGids;
515    final SparseArray<ArraySet<String>> mSystemPermissions;
516    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
517
518    // If mac_permissions.xml was found for seinfo labeling.
519    boolean mFoundPolicyFile;
520
521    // If a recursive restorecon of /data/data/<pkg> is needed.
522    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
523
524    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
525
526    public static final class SharedLibraryEntry {
527        public final String path;
528        public final String apk;
529
530        SharedLibraryEntry(String _path, String _apk) {
531            path = _path;
532            apk = _apk;
533        }
534    }
535
536    // Currently known shared libraries.
537    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
538            new ArrayMap<String, SharedLibraryEntry>();
539
540    // All available activities, for your resolving pleasure.
541    final ActivityIntentResolver mActivities =
542            new ActivityIntentResolver();
543
544    // All available receivers, for your resolving pleasure.
545    final ActivityIntentResolver mReceivers =
546            new ActivityIntentResolver();
547
548    // All available services, for your resolving pleasure.
549    final ServiceIntentResolver mServices = new ServiceIntentResolver();
550
551    // All available providers, for your resolving pleasure.
552    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
553
554    // Mapping from provider base names (first directory in content URI codePath)
555    // to the provider information.
556    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
557            new ArrayMap<String, PackageParser.Provider>();
558
559    // Mapping from instrumentation class names to info about them.
560    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
561            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
562
563    // Mapping from permission names to info about them.
564    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
565            new ArrayMap<String, PackageParser.PermissionGroup>();
566
567    // Packages whose data we have transfered into another package, thus
568    // should no longer exist.
569    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
570
571    // Broadcast actions that are only available to the system.
572    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
573
574    /** List of packages waiting for verification. */
575    final SparseArray<PackageVerificationState> mPendingVerification
576            = new SparseArray<PackageVerificationState>();
577
578    /** Set of packages associated with each app op permission. */
579    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
580
581    final PackageInstallerService mInstallerService;
582
583    private final PackageDexOptimizer mPackageDexOptimizer;
584
585    private AtomicInteger mNextMoveId = new AtomicInteger();
586    private final MoveCallbacks mMoveCallbacks;
587
588    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
589
590    // Cache of users who need badging.
591    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
592
593    /** Token for keys in mPendingVerification. */
594    private int mPendingVerificationToken = 0;
595
596    volatile boolean mSystemReady;
597    volatile boolean mSafeMode;
598    volatile boolean mHasSystemUidErrors;
599
600    ApplicationInfo mAndroidApplication;
601    final ActivityInfo mResolveActivity = new ActivityInfo();
602    final ResolveInfo mResolveInfo = new ResolveInfo();
603    ComponentName mResolveComponentName;
604    PackageParser.Package mPlatformPackage;
605    ComponentName mCustomResolverComponentName;
606
607    boolean mResolverReplaced = false;
608
609    private final @Nullable ComponentName mIntentFilterVerifierComponent;
610    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
611
612    private int mIntentFilterVerificationToken = 0;
613
614    /** Component that knows whether or not an ephemeral application exists */
615    final ComponentName mEphemeralResolverComponent;
616    /** The service connection to the ephemeral resolver */
617    final EphemeralResolverConnection mEphemeralResolverConnection;
618
619    /** Component used to install ephemeral applications */
620    final ComponentName mEphemeralInstallerComponent;
621    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
622    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
623
624    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
625            = new SparseArray<IntentFilterVerificationState>();
626
627    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
628            new DefaultPermissionGrantPolicy(this);
629
630    // List of packages names to keep cached, even if they are uninstalled for all users
631    private List<String> mKeepUninstalledPackages;
632
633    private static class IFVerificationParams {
634        PackageParser.Package pkg;
635        boolean replacing;
636        int userId;
637        int verifierUid;
638
639        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
640                int _userId, int _verifierUid) {
641            pkg = _pkg;
642            replacing = _replacing;
643            userId = _userId;
644            replacing = _replacing;
645            verifierUid = _verifierUid;
646        }
647    }
648
649    private interface IntentFilterVerifier<T extends IntentFilter> {
650        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
651                                               T filter, String packageName);
652        void startVerifications(int userId);
653        void receiveVerificationResponse(int verificationId);
654    }
655
656    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
657        private Context mContext;
658        private ComponentName mIntentFilterVerifierComponent;
659        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
660
661        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
662            mContext = context;
663            mIntentFilterVerifierComponent = verifierComponent;
664        }
665
666        private String getDefaultScheme() {
667            return IntentFilter.SCHEME_HTTPS;
668        }
669
670        @Override
671        public void startVerifications(int userId) {
672            // Launch verifications requests
673            int count = mCurrentIntentFilterVerifications.size();
674            for (int n=0; n<count; n++) {
675                int verificationId = mCurrentIntentFilterVerifications.get(n);
676                final IntentFilterVerificationState ivs =
677                        mIntentFilterVerificationStates.get(verificationId);
678
679                String packageName = ivs.getPackageName();
680
681                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
682                final int filterCount = filters.size();
683                ArraySet<String> domainsSet = new ArraySet<>();
684                for (int m=0; m<filterCount; m++) {
685                    PackageParser.ActivityIntentInfo filter = filters.get(m);
686                    domainsSet.addAll(filter.getHostsList());
687                }
688                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
689                synchronized (mPackages) {
690                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
691                            packageName, domainsList) != null) {
692                        scheduleWriteSettingsLocked();
693                    }
694                }
695                sendVerificationRequest(userId, verificationId, ivs);
696            }
697            mCurrentIntentFilterVerifications.clear();
698        }
699
700        private void sendVerificationRequest(int userId, int verificationId,
701                IntentFilterVerificationState ivs) {
702
703            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
706                    verificationId);
707            verificationIntent.putExtra(
708                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
709                    getDefaultScheme());
710            verificationIntent.putExtra(
711                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
712                    ivs.getHostsString());
713            verificationIntent.putExtra(
714                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
715                    ivs.getPackageName());
716            verificationIntent.setComponent(mIntentFilterVerifierComponent);
717            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
718
719            UserHandle user = new UserHandle(userId);
720            mContext.sendBroadcastAsUser(verificationIntent, user);
721            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
722                    "Sending IntentFilter verification broadcast");
723        }
724
725        public void receiveVerificationResponse(int verificationId) {
726            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
727
728            final boolean verified = ivs.isVerified();
729
730            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
731            final int count = filters.size();
732            if (DEBUG_DOMAIN_VERIFICATION) {
733                Slog.i(TAG, "Received verification response " + verificationId
734                        + " for " + count + " filters, verified=" + verified);
735            }
736            for (int n=0; n<count; n++) {
737                PackageParser.ActivityIntentInfo filter = filters.get(n);
738                filter.setVerified(verified);
739
740                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
741                        + " verified with result:" + verified + " and hosts:"
742                        + ivs.getHostsString());
743            }
744
745            mIntentFilterVerificationStates.remove(verificationId);
746
747            final String packageName = ivs.getPackageName();
748            IntentFilterVerificationInfo ivi = null;
749
750            synchronized (mPackages) {
751                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
752            }
753            if (ivi == null) {
754                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
755                        + verificationId + " packageName:" + packageName);
756                return;
757            }
758            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
759                    "Updating IntentFilterVerificationInfo for package " + packageName
760                            +" verificationId:" + verificationId);
761
762            synchronized (mPackages) {
763                if (verified) {
764                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
765                } else {
766                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
767                }
768                scheduleWriteSettingsLocked();
769
770                final int userId = ivs.getUserId();
771                if (userId != UserHandle.USER_ALL) {
772                    final int userStatus =
773                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
774
775                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
776                    boolean needUpdate = false;
777
778                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
779                    // already been set by the User thru the Disambiguation dialog
780                    switch (userStatus) {
781                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
782                            if (verified) {
783                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
784                            } else {
785                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
786                            }
787                            needUpdate = true;
788                            break;
789
790                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
791                            if (verified) {
792                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
793                                needUpdate = true;
794                            }
795                            break;
796
797                        default:
798                            // Nothing to do
799                    }
800
801                    if (needUpdate) {
802                        mSettings.updateIntentFilterVerificationStatusLPw(
803                                packageName, updatedStatus, userId);
804                        scheduleWritePackageRestrictionsLocked(userId);
805                    }
806                }
807            }
808        }
809
810        @Override
811        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
812                    ActivityIntentInfo filter, String packageName) {
813            if (!hasValidDomains(filter)) {
814                return false;
815            }
816            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
817            if (ivs == null) {
818                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
819                        packageName);
820            }
821            if (DEBUG_DOMAIN_VERIFICATION) {
822                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
823            }
824            ivs.addFilter(filter);
825            return true;
826        }
827
828        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
829                int userId, int verificationId, String packageName) {
830            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
831                    verifierUid, userId, packageName);
832            ivs.setPendingState();
833            synchronized (mPackages) {
834                mIntentFilterVerificationStates.append(verificationId, ivs);
835                mCurrentIntentFilterVerifications.add(verificationId);
836            }
837            return ivs;
838        }
839    }
840
841    private static boolean hasValidDomains(ActivityIntentInfo filter) {
842        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
843                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
844                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
845    }
846
847    // Set of pending broadcasts for aggregating enable/disable of components.
848    static class PendingPackageBroadcasts {
849        // for each user id, a map of <package name -> components within that package>
850        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
851
852        public PendingPackageBroadcasts() {
853            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
854        }
855
856        public ArrayList<String> get(int userId, String packageName) {
857            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
858            return packages.get(packageName);
859        }
860
861        public void put(int userId, String packageName, ArrayList<String> components) {
862            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
863            packages.put(packageName, components);
864        }
865
866        public void remove(int userId, String packageName) {
867            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
868            if (packages != null) {
869                packages.remove(packageName);
870            }
871        }
872
873        public void remove(int userId) {
874            mUidMap.remove(userId);
875        }
876
877        public int userIdCount() {
878            return mUidMap.size();
879        }
880
881        public int userIdAt(int n) {
882            return mUidMap.keyAt(n);
883        }
884
885        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
886            return mUidMap.get(userId);
887        }
888
889        public int size() {
890            // total number of pending broadcast entries across all userIds
891            int num = 0;
892            for (int i = 0; i< mUidMap.size(); i++) {
893                num += mUidMap.valueAt(i).size();
894            }
895            return num;
896        }
897
898        public void clear() {
899            mUidMap.clear();
900        }
901
902        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
903            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
904            if (map == null) {
905                map = new ArrayMap<String, ArrayList<String>>();
906                mUidMap.put(userId, map);
907            }
908            return map;
909        }
910    }
911    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
912
913    // Service Connection to remote media container service to copy
914    // package uri's from external media onto secure containers
915    // or internal storage.
916    private IMediaContainerService mContainerService = null;
917
918    static final int SEND_PENDING_BROADCAST = 1;
919    static final int MCS_BOUND = 3;
920    static final int END_COPY = 4;
921    static final int INIT_COPY = 5;
922    static final int MCS_UNBIND = 6;
923    static final int START_CLEANING_PACKAGE = 7;
924    static final int FIND_INSTALL_LOC = 8;
925    static final int POST_INSTALL = 9;
926    static final int MCS_RECONNECT = 10;
927    static final int MCS_GIVE_UP = 11;
928    static final int UPDATED_MEDIA_STATUS = 12;
929    static final int WRITE_SETTINGS = 13;
930    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
931    static final int PACKAGE_VERIFIED = 15;
932    static final int CHECK_PENDING_VERIFICATION = 16;
933    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
934    static final int INTENT_FILTER_VERIFIED = 18;
935
936    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
937
938    // Delay time in millisecs
939    static final int BROADCAST_DELAY = 10 * 1000;
940
941    static UserManagerService sUserManager;
942
943    // Stores a list of users whose package restrictions file needs to be updated
944    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
945
946    final private DefaultContainerConnection mDefContainerConn =
947            new DefaultContainerConnection();
948    class DefaultContainerConnection implements ServiceConnection {
949        public void onServiceConnected(ComponentName name, IBinder service) {
950            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
951            IMediaContainerService imcs =
952                IMediaContainerService.Stub.asInterface(service);
953            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
954        }
955
956        public void onServiceDisconnected(ComponentName name) {
957            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
958        }
959    }
960
961    // Recordkeeping of restore-after-install operations that are currently in flight
962    // between the Package Manager and the Backup Manager
963    static class PostInstallData {
964        public InstallArgs args;
965        public PackageInstalledInfo res;
966
967        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
968            args = _a;
969            res = _r;
970        }
971    }
972
973    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
974    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
975
976    // XML tags for backup/restore of various bits of state
977    private static final String TAG_PREFERRED_BACKUP = "pa";
978    private static final String TAG_DEFAULT_APPS = "da";
979    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
980
981    final @Nullable String mRequiredVerifierPackage;
982    final @Nullable String mRequiredInstallerPackage;
983
984    private final PackageUsage mPackageUsage = new PackageUsage();
985
986    private class PackageUsage {
987        private static final int WRITE_INTERVAL
988            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
989
990        private final Object mFileLock = new Object();
991        private final AtomicLong mLastWritten = new AtomicLong(0);
992        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
993
994        private boolean mIsHistoricalPackageUsageAvailable = true;
995
996        boolean isHistoricalPackageUsageAvailable() {
997            return mIsHistoricalPackageUsageAvailable;
998        }
999
1000        void write(boolean force) {
1001            if (force) {
1002                writeInternal();
1003                return;
1004            }
1005            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1006                && !DEBUG_DEXOPT) {
1007                return;
1008            }
1009            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1010                new Thread("PackageUsage_DiskWriter") {
1011                    @Override
1012                    public void run() {
1013                        try {
1014                            writeInternal();
1015                        } finally {
1016                            mBackgroundWriteRunning.set(false);
1017                        }
1018                    }
1019                }.start();
1020            }
1021        }
1022
1023        private void writeInternal() {
1024            synchronized (mPackages) {
1025                synchronized (mFileLock) {
1026                    AtomicFile file = getFile();
1027                    FileOutputStream f = null;
1028                    try {
1029                        f = file.startWrite();
1030                        BufferedOutputStream out = new BufferedOutputStream(f);
1031                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1032                        StringBuilder sb = new StringBuilder();
1033                        for (PackageParser.Package pkg : mPackages.values()) {
1034                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1035                                continue;
1036                            }
1037                            sb.setLength(0);
1038                            sb.append(pkg.packageName);
1039                            sb.append(' ');
1040                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1041                            sb.append('\n');
1042                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1043                        }
1044                        out.flush();
1045                        file.finishWrite(f);
1046                    } catch (IOException e) {
1047                        if (f != null) {
1048                            file.failWrite(f);
1049                        }
1050                        Log.e(TAG, "Failed to write package usage times", e);
1051                    }
1052                }
1053            }
1054            mLastWritten.set(SystemClock.elapsedRealtime());
1055        }
1056
1057        void readLP() {
1058            synchronized (mFileLock) {
1059                AtomicFile file = getFile();
1060                BufferedInputStream in = null;
1061                try {
1062                    in = new BufferedInputStream(file.openRead());
1063                    StringBuffer sb = new StringBuffer();
1064                    while (true) {
1065                        String packageName = readToken(in, sb, ' ');
1066                        if (packageName == null) {
1067                            break;
1068                        }
1069                        String timeInMillisString = readToken(in, sb, '\n');
1070                        if (timeInMillisString == null) {
1071                            throw new IOException("Failed to find last usage time for package "
1072                                                  + packageName);
1073                        }
1074                        PackageParser.Package pkg = mPackages.get(packageName);
1075                        if (pkg == null) {
1076                            continue;
1077                        }
1078                        long timeInMillis;
1079                        try {
1080                            timeInMillis = Long.parseLong(timeInMillisString);
1081                        } catch (NumberFormatException e) {
1082                            throw new IOException("Failed to parse " + timeInMillisString
1083                                                  + " as a long.", e);
1084                        }
1085                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1086                    }
1087                } catch (FileNotFoundException expected) {
1088                    mIsHistoricalPackageUsageAvailable = false;
1089                } catch (IOException e) {
1090                    Log.w(TAG, "Failed to read package usage times", e);
1091                } finally {
1092                    IoUtils.closeQuietly(in);
1093                }
1094            }
1095            mLastWritten.set(SystemClock.elapsedRealtime());
1096        }
1097
1098        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1099                throws IOException {
1100            sb.setLength(0);
1101            while (true) {
1102                int ch = in.read();
1103                if (ch == -1) {
1104                    if (sb.length() == 0) {
1105                        return null;
1106                    }
1107                    throw new IOException("Unexpected EOF");
1108                }
1109                if (ch == endOfToken) {
1110                    return sb.toString();
1111                }
1112                sb.append((char)ch);
1113            }
1114        }
1115
1116        private AtomicFile getFile() {
1117            File dataDir = Environment.getDataDirectory();
1118            File systemDir = new File(dataDir, "system");
1119            File fname = new File(systemDir, "package-usage.list");
1120            return new AtomicFile(fname);
1121        }
1122    }
1123
1124    class PackageHandler extends Handler {
1125        private boolean mBound = false;
1126        final ArrayList<HandlerParams> mPendingInstalls =
1127            new ArrayList<HandlerParams>();
1128
1129        private boolean connectToService() {
1130            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1131                    " DefaultContainerService");
1132            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1133            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1134            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1135                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1136                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137                mBound = true;
1138                return true;
1139            }
1140            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1141            return false;
1142        }
1143
1144        private void disconnectService() {
1145            mContainerService = null;
1146            mBound = false;
1147            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1148            mContext.unbindService(mDefContainerConn);
1149            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150        }
1151
1152        PackageHandler(Looper looper) {
1153            super(looper);
1154        }
1155
1156        public void handleMessage(Message msg) {
1157            try {
1158                doHandleMessage(msg);
1159            } finally {
1160                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1161            }
1162        }
1163
1164        void doHandleMessage(Message msg) {
1165            switch (msg.what) {
1166                case INIT_COPY: {
1167                    HandlerParams params = (HandlerParams) msg.obj;
1168                    int idx = mPendingInstalls.size();
1169                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1170                    // If a bind was already initiated we dont really
1171                    // need to do anything. The pending install
1172                    // will be processed later on.
1173                    if (!mBound) {
1174                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1175                                System.identityHashCode(mHandler));
1176                        // If this is the only one pending we might
1177                        // have to bind to the service again.
1178                        if (!connectToService()) {
1179                            Slog.e(TAG, "Failed to bind to media container service");
1180                            params.serviceError();
1181                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1182                                    System.identityHashCode(mHandler));
1183                            if (params.traceMethod != null) {
1184                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1185                                        params.traceCookie);
1186                            }
1187                            return;
1188                        } else {
1189                            // Once we bind to the service, the first
1190                            // pending request will be processed.
1191                            mPendingInstalls.add(idx, params);
1192                        }
1193                    } else {
1194                        mPendingInstalls.add(idx, params);
1195                        // Already bound to the service. Just make
1196                        // sure we trigger off processing the first request.
1197                        if (idx == 0) {
1198                            mHandler.sendEmptyMessage(MCS_BOUND);
1199                        }
1200                    }
1201                    break;
1202                }
1203                case MCS_BOUND: {
1204                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1205                    if (msg.obj != null) {
1206                        mContainerService = (IMediaContainerService) msg.obj;
1207                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1208                                System.identityHashCode(mHandler));
1209                    }
1210                    if (mContainerService == null) {
1211                        if (!mBound) {
1212                            // Something seriously wrong since we are not bound and we are not
1213                            // waiting for connection. Bail out.
1214                            Slog.e(TAG, "Cannot bind to media container service");
1215                            for (HandlerParams params : mPendingInstalls) {
1216                                // Indicate service bind error
1217                                params.serviceError();
1218                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1219                                        System.identityHashCode(params));
1220                                if (params.traceMethod != null) {
1221                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1222                                            params.traceMethod, params.traceCookie);
1223                                }
1224                                return;
1225                            }
1226                            mPendingInstalls.clear();
1227                        } else {
1228                            Slog.w(TAG, "Waiting to connect to media container service");
1229                        }
1230                    } else if (mPendingInstalls.size() > 0) {
1231                        HandlerParams params = mPendingInstalls.get(0);
1232                        if (params != null) {
1233                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1234                                    System.identityHashCode(params));
1235                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1236                            if (params.startCopy()) {
1237                                // We are done...  look for more work or to
1238                                // go idle.
1239                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1240                                        "Checking for more work or unbind...");
1241                                // Delete pending install
1242                                if (mPendingInstalls.size() > 0) {
1243                                    mPendingInstalls.remove(0);
1244                                }
1245                                if (mPendingInstalls.size() == 0) {
1246                                    if (mBound) {
1247                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1248                                                "Posting delayed MCS_UNBIND");
1249                                        removeMessages(MCS_UNBIND);
1250                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1251                                        // Unbind after a little delay, to avoid
1252                                        // continual thrashing.
1253                                        sendMessageDelayed(ubmsg, 10000);
1254                                    }
1255                                } else {
1256                                    // There are more pending requests in queue.
1257                                    // Just post MCS_BOUND message to trigger processing
1258                                    // of next pending install.
1259                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1260                                            "Posting MCS_BOUND for next work");
1261                                    mHandler.sendEmptyMessage(MCS_BOUND);
1262                                }
1263                            }
1264                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1265                        }
1266                    } else {
1267                        // Should never happen ideally.
1268                        Slog.w(TAG, "Empty queue");
1269                    }
1270                    break;
1271                }
1272                case MCS_RECONNECT: {
1273                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1274                    if (mPendingInstalls.size() > 0) {
1275                        if (mBound) {
1276                            disconnectService();
1277                        }
1278                        if (!connectToService()) {
1279                            Slog.e(TAG, "Failed to bind to media container service");
1280                            for (HandlerParams params : mPendingInstalls) {
1281                                // Indicate service bind error
1282                                params.serviceError();
1283                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1284                                        System.identityHashCode(params));
1285                            }
1286                            mPendingInstalls.clear();
1287                        }
1288                    }
1289                    break;
1290                }
1291                case MCS_UNBIND: {
1292                    // If there is no actual work left, then time to unbind.
1293                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1294
1295                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1296                        if (mBound) {
1297                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1298
1299                            disconnectService();
1300                        }
1301                    } else if (mPendingInstalls.size() > 0) {
1302                        // There are more pending requests in queue.
1303                        // Just post MCS_BOUND message to trigger processing
1304                        // of next pending install.
1305                        mHandler.sendEmptyMessage(MCS_BOUND);
1306                    }
1307
1308                    break;
1309                }
1310                case MCS_GIVE_UP: {
1311                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1312                    HandlerParams params = mPendingInstalls.remove(0);
1313                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1314                            System.identityHashCode(params));
1315                    break;
1316                }
1317                case SEND_PENDING_BROADCAST: {
1318                    String packages[];
1319                    ArrayList<String> components[];
1320                    int size = 0;
1321                    int uids[];
1322                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1323                    synchronized (mPackages) {
1324                        if (mPendingBroadcasts == null) {
1325                            return;
1326                        }
1327                        size = mPendingBroadcasts.size();
1328                        if (size <= 0) {
1329                            // Nothing to be done. Just return
1330                            return;
1331                        }
1332                        packages = new String[size];
1333                        components = new ArrayList[size];
1334                        uids = new int[size];
1335                        int i = 0;  // filling out the above arrays
1336
1337                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1338                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1339                            Iterator<Map.Entry<String, ArrayList<String>>> it
1340                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1341                                            .entrySet().iterator();
1342                            while (it.hasNext() && i < size) {
1343                                Map.Entry<String, ArrayList<String>> ent = it.next();
1344                                packages[i] = ent.getKey();
1345                                components[i] = ent.getValue();
1346                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1347                                uids[i] = (ps != null)
1348                                        ? UserHandle.getUid(packageUserId, ps.appId)
1349                                        : -1;
1350                                i++;
1351                            }
1352                        }
1353                        size = i;
1354                        mPendingBroadcasts.clear();
1355                    }
1356                    // Send broadcasts
1357                    for (int i = 0; i < size; i++) {
1358                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1359                    }
1360                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1361                    break;
1362                }
1363                case START_CLEANING_PACKAGE: {
1364                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1365                    final String packageName = (String)msg.obj;
1366                    final int userId = msg.arg1;
1367                    final boolean andCode = msg.arg2 != 0;
1368                    synchronized (mPackages) {
1369                        if (userId == UserHandle.USER_ALL) {
1370                            int[] users = sUserManager.getUserIds();
1371                            for (int user : users) {
1372                                mSettings.addPackageToCleanLPw(
1373                                        new PackageCleanItem(user, packageName, andCode));
1374                            }
1375                        } else {
1376                            mSettings.addPackageToCleanLPw(
1377                                    new PackageCleanItem(userId, packageName, andCode));
1378                        }
1379                    }
1380                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1381                    startCleaningPackages();
1382                } break;
1383                case POST_INSTALL: {
1384                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1385
1386                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1387                    mRunningInstalls.delete(msg.arg1);
1388                    boolean deleteOld = false;
1389
1390                    if (data != null) {
1391                        InstallArgs args = data.args;
1392                        PackageInstalledInfo res = data.res;
1393
1394                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1395                            final String packageName = res.pkg.applicationInfo.packageName;
1396                            res.removedInfo.sendBroadcast(false, true, false);
1397                            Bundle extras = new Bundle(1);
1398                            extras.putInt(Intent.EXTRA_UID, res.uid);
1399
1400                            // Now that we successfully installed the package, grant runtime
1401                            // permissions if requested before broadcasting the install.
1402                            if ((args.installFlags
1403                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1404                                    && res.pkg.applicationInfo.targetSdkVersion
1405                                            >= Build.VERSION_CODES.M) {
1406                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1407                                        args.installGrantPermissions);
1408                            }
1409
1410                            synchronized (mPackages) {
1411                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1412                            }
1413
1414                            // Determine the set of users who are adding this
1415                            // package for the first time vs. those who are seeing
1416                            // an update.
1417                            int[] firstUsers;
1418                            int[] updateUsers = new int[0];
1419                            if (res.origUsers == null || res.origUsers.length == 0) {
1420                                firstUsers = res.newUsers;
1421                            } else {
1422                                firstUsers = new int[0];
1423                                for (int i=0; i<res.newUsers.length; i++) {
1424                                    int user = res.newUsers[i];
1425                                    boolean isNew = true;
1426                                    for (int j=0; j<res.origUsers.length; j++) {
1427                                        if (res.origUsers[j] == user) {
1428                                            isNew = false;
1429                                            break;
1430                                        }
1431                                    }
1432                                    if (isNew) {
1433                                        int[] newFirst = new int[firstUsers.length+1];
1434                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1435                                                firstUsers.length);
1436                                        newFirst[firstUsers.length] = user;
1437                                        firstUsers = newFirst;
1438                                    } else {
1439                                        int[] newUpdate = new int[updateUsers.length+1];
1440                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1441                                                updateUsers.length);
1442                                        newUpdate[updateUsers.length] = user;
1443                                        updateUsers = newUpdate;
1444                                    }
1445                                }
1446                            }
1447                            // don't broadcast for ephemeral installs/updates
1448                            final boolean isEphemeral = isEphemeral(res.pkg);
1449                            if (!isEphemeral) {
1450                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1451                                        extras, 0 /*flags*/, null /*targetPackage*/,
1452                                        null /*finishedReceiver*/, firstUsers);
1453                            }
1454                            final boolean update = res.removedInfo.removedPackage != null;
1455                            if (update) {
1456                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1457                            }
1458                            if (!isEphemeral) {
1459                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1460                                        extras, 0 /*flags*/, null /*targetPackage*/,
1461                                        null /*finishedReceiver*/, updateUsers);
1462                            }
1463                            if (update) {
1464                                if (!isEphemeral) {
1465                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1466                                            packageName, extras, 0 /*flags*/,
1467                                            null /*targetPackage*/, null /*finishedReceiver*/,
1468                                            updateUsers);
1469                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1470                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1471                                            packageName /*targetPackage*/,
1472                                            null /*finishedReceiver*/, updateUsers);
1473                                }
1474
1475                                // treat asec-hosted packages like removable media on upgrade
1476                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1477                                    if (DEBUG_INSTALL) {
1478                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1479                                                + " is ASEC-hosted -> AVAILABLE");
1480                                    }
1481                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1482                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1483                                    pkgList.add(packageName);
1484                                    sendResourcesChangedBroadcast(true, true,
1485                                            pkgList,uidArray, null);
1486                                }
1487                            }
1488                            if (res.removedInfo.args != null) {
1489                                // Remove the replaced package's older resources safely now
1490                                deleteOld = true;
1491                            }
1492
1493                            // If this app is a browser and it's newly-installed for some
1494                            // users, clear any default-browser state in those users
1495                            if (firstUsers.length > 0) {
1496                                // the app's nature doesn't depend on the user, so we can just
1497                                // check its browser nature in any user and generalize.
1498                                if (packageIsBrowser(packageName, firstUsers[0])) {
1499                                    synchronized (mPackages) {
1500                                        for (int userId : firstUsers) {
1501                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1502                                        }
1503                                    }
1504                                }
1505                            }
1506                            // Log current value of "unknown sources" setting
1507                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1508                                getUnknownSourcesSettings());
1509                        }
1510                        // Force a gc to clear up things
1511                        Runtime.getRuntime().gc();
1512                        // We delete after a gc for applications  on sdcard.
1513                        if (deleteOld) {
1514                            synchronized (mInstallLock) {
1515                                res.removedInfo.args.doPostDeleteLI(true);
1516                            }
1517                        }
1518                        if (args.observer != null) {
1519                            try {
1520                                Bundle extras = extrasForInstallResult(res);
1521                                args.observer.onPackageInstalled(res.name, res.returnCode,
1522                                        res.returnMsg, extras);
1523                            } catch (RemoteException e) {
1524                                Slog.i(TAG, "Observer no longer exists.");
1525                            }
1526                        }
1527                        if (args.traceMethod != null) {
1528                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1529                                    args.traceCookie);
1530                        }
1531                        return;
1532                    } else {
1533                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1534                    }
1535
1536                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1537                } break;
1538                case UPDATED_MEDIA_STATUS: {
1539                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1540                    boolean reportStatus = msg.arg1 == 1;
1541                    boolean doGc = msg.arg2 == 1;
1542                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1543                    if (doGc) {
1544                        // Force a gc to clear up stale containers.
1545                        Runtime.getRuntime().gc();
1546                    }
1547                    if (msg.obj != null) {
1548                        @SuppressWarnings("unchecked")
1549                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1550                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1551                        // Unload containers
1552                        unloadAllContainers(args);
1553                    }
1554                    if (reportStatus) {
1555                        try {
1556                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1557                            PackageHelper.getMountService().finishMediaUpdate();
1558                        } catch (RemoteException e) {
1559                            Log.e(TAG, "MountService not running?");
1560                        }
1561                    }
1562                } break;
1563                case WRITE_SETTINGS: {
1564                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1565                    synchronized (mPackages) {
1566                        removeMessages(WRITE_SETTINGS);
1567                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1568                        mSettings.writeLPr();
1569                        mDirtyUsers.clear();
1570                    }
1571                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1572                } break;
1573                case WRITE_PACKAGE_RESTRICTIONS: {
1574                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1575                    synchronized (mPackages) {
1576                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1577                        for (int userId : mDirtyUsers) {
1578                            mSettings.writePackageRestrictionsLPr(userId);
1579                        }
1580                        mDirtyUsers.clear();
1581                    }
1582                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1583                } break;
1584                case CHECK_PENDING_VERIFICATION: {
1585                    final int verificationId = msg.arg1;
1586                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1587
1588                    if ((state != null) && !state.timeoutExtended()) {
1589                        final InstallArgs args = state.getInstallArgs();
1590                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1591
1592                        Slog.i(TAG, "Verification timed out for " + originUri);
1593                        mPendingVerification.remove(verificationId);
1594
1595                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1596
1597                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1598                            Slog.i(TAG, "Continuing with installation of " + originUri);
1599                            state.setVerifierResponse(Binder.getCallingUid(),
1600                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1601                            broadcastPackageVerified(verificationId, originUri,
1602                                    PackageManager.VERIFICATION_ALLOW,
1603                                    state.getInstallArgs().getUser());
1604                            try {
1605                                ret = args.copyApk(mContainerService, true);
1606                            } catch (RemoteException e) {
1607                                Slog.e(TAG, "Could not contact the ContainerService");
1608                            }
1609                        } else {
1610                            broadcastPackageVerified(verificationId, originUri,
1611                                    PackageManager.VERIFICATION_REJECT,
1612                                    state.getInstallArgs().getUser());
1613                        }
1614
1615                        Trace.asyncTraceEnd(
1616                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1617
1618                        processPendingInstall(args, ret);
1619                        mHandler.sendEmptyMessage(MCS_UNBIND);
1620                    }
1621                    break;
1622                }
1623                case PACKAGE_VERIFIED: {
1624                    final int verificationId = msg.arg1;
1625
1626                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1627                    if (state == null) {
1628                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1629                        break;
1630                    }
1631
1632                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1633
1634                    state.setVerifierResponse(response.callerUid, response.code);
1635
1636                    if (state.isVerificationComplete()) {
1637                        mPendingVerification.remove(verificationId);
1638
1639                        final InstallArgs args = state.getInstallArgs();
1640                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1641
1642                        int ret;
1643                        if (state.isInstallAllowed()) {
1644                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1645                            broadcastPackageVerified(verificationId, originUri,
1646                                    response.code, state.getInstallArgs().getUser());
1647                            try {
1648                                ret = args.copyApk(mContainerService, true);
1649                            } catch (RemoteException e) {
1650                                Slog.e(TAG, "Could not contact the ContainerService");
1651                            }
1652                        } else {
1653                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1654                        }
1655
1656                        Trace.asyncTraceEnd(
1657                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1658
1659                        processPendingInstall(args, ret);
1660                        mHandler.sendEmptyMessage(MCS_UNBIND);
1661                    }
1662
1663                    break;
1664                }
1665                case START_INTENT_FILTER_VERIFICATIONS: {
1666                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1667                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1668                            params.replacing, params.pkg);
1669                    break;
1670                }
1671                case INTENT_FILTER_VERIFIED: {
1672                    final int verificationId = msg.arg1;
1673
1674                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1675                            verificationId);
1676                    if (state == null) {
1677                        Slog.w(TAG, "Invalid IntentFilter verification token "
1678                                + verificationId + " received");
1679                        break;
1680                    }
1681
1682                    final int userId = state.getUserId();
1683
1684                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1685                            "Processing IntentFilter verification with token:"
1686                            + verificationId + " and userId:" + userId);
1687
1688                    final IntentFilterVerificationResponse response =
1689                            (IntentFilterVerificationResponse) msg.obj;
1690
1691                    state.setVerifierResponse(response.callerUid, response.code);
1692
1693                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1694                            "IntentFilter verification with token:" + verificationId
1695                            + " and userId:" + userId
1696                            + " is settings verifier response with response code:"
1697                            + response.code);
1698
1699                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1700                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1701                                + response.getFailedDomainsString());
1702                    }
1703
1704                    if (state.isVerificationComplete()) {
1705                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1706                    } else {
1707                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1708                                "IntentFilter verification with token:" + verificationId
1709                                + " was not said to be complete");
1710                    }
1711
1712                    break;
1713                }
1714            }
1715        }
1716    }
1717
1718    private StorageEventListener mStorageListener = new StorageEventListener() {
1719        @Override
1720        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1721            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1722                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1723                    final String volumeUuid = vol.getFsUuid();
1724
1725                    // Clean up any users or apps that were removed or recreated
1726                    // while this volume was missing
1727                    reconcileUsers(volumeUuid);
1728                    reconcileApps(volumeUuid);
1729
1730                    // Clean up any install sessions that expired or were
1731                    // cancelled while this volume was missing
1732                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1733
1734                    loadPrivatePackages(vol);
1735
1736                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1737                    unloadPrivatePackages(vol);
1738                }
1739            }
1740
1741            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1742                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1743                    updateExternalMediaStatus(true, false);
1744                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1745                    updateExternalMediaStatus(false, false);
1746                }
1747            }
1748        }
1749
1750        @Override
1751        public void onVolumeForgotten(String fsUuid) {
1752            if (TextUtils.isEmpty(fsUuid)) {
1753                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1754                return;
1755            }
1756
1757            // Remove any apps installed on the forgotten volume
1758            synchronized (mPackages) {
1759                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1760                for (PackageSetting ps : packages) {
1761                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1762                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1763                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1764                }
1765
1766                mSettings.onVolumeForgotten(fsUuid);
1767                mSettings.writeLPr();
1768            }
1769        }
1770    };
1771
1772    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1773            String[] grantedPermissions) {
1774        if (userId >= UserHandle.USER_SYSTEM) {
1775            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1776        } else if (userId == UserHandle.USER_ALL) {
1777            final int[] userIds;
1778            synchronized (mPackages) {
1779                userIds = UserManagerService.getInstance().getUserIds();
1780            }
1781            for (int someUserId : userIds) {
1782                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1783            }
1784        }
1785
1786        // We could have touched GID membership, so flush out packages.list
1787        synchronized (mPackages) {
1788            mSettings.writePackageListLPr();
1789        }
1790    }
1791
1792    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1793            String[] grantedPermissions) {
1794        SettingBase sb = (SettingBase) pkg.mExtras;
1795        if (sb == null) {
1796            return;
1797        }
1798
1799        PermissionsState permissionsState = sb.getPermissionsState();
1800
1801        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1802                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1803
1804        synchronized (mPackages) {
1805            for (String permission : pkg.requestedPermissions) {
1806                BasePermission bp = mSettings.mPermissions.get(permission);
1807                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1808                        && (grantedPermissions == null
1809                               || ArrayUtils.contains(grantedPermissions, permission))) {
1810                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1811                    // Installer cannot change immutable permissions.
1812                    if ((flags & immutableFlags) == 0) {
1813                        grantRuntimePermission(pkg.packageName, permission, userId);
1814                    }
1815                }
1816            }
1817        }
1818    }
1819
1820    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1821        Bundle extras = null;
1822        switch (res.returnCode) {
1823            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1824                extras = new Bundle();
1825                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1826                        res.origPermission);
1827                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1828                        res.origPackage);
1829                break;
1830            }
1831            case PackageManager.INSTALL_SUCCEEDED: {
1832                extras = new Bundle();
1833                extras.putBoolean(Intent.EXTRA_REPLACING,
1834                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1835                break;
1836            }
1837        }
1838        return extras;
1839    }
1840
1841    void scheduleWriteSettingsLocked() {
1842        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1843            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1844        }
1845    }
1846
1847    void scheduleWritePackageRestrictionsLocked(int userId) {
1848        if (!sUserManager.exists(userId)) return;
1849        mDirtyUsers.add(userId);
1850        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1851            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1852        }
1853    }
1854
1855    public static PackageManagerService main(Context context, Installer installer,
1856            boolean factoryTest, boolean onlyCore) {
1857        PackageManagerService m = new PackageManagerService(context, installer,
1858                factoryTest, onlyCore);
1859        m.enableSystemUserPackages();
1860        ServiceManager.addService("package", m);
1861        return m;
1862    }
1863
1864    private void enableSystemUserPackages() {
1865        if (!UserManager.isSplitSystemUser()) {
1866            return;
1867        }
1868        // For system user, enable apps based on the following conditions:
1869        // - app is whitelisted or belong to one of these groups:
1870        //   -- system app which has no launcher icons
1871        //   -- system app which has INTERACT_ACROSS_USERS permission
1872        //   -- system IME app
1873        // - app is not in the blacklist
1874        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1875        Set<String> enableApps = new ArraySet<>();
1876        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1877                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1878                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1879        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1880        enableApps.addAll(wlApps);
1881        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1882                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1883        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1884        enableApps.removeAll(blApps);
1885        Log.i(TAG, "Applications installed for system user: " + enableApps);
1886        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1887                UserHandle.SYSTEM);
1888        final int allAppsSize = allAps.size();
1889        synchronized (mPackages) {
1890            for (int i = 0; i < allAppsSize; i++) {
1891                String pName = allAps.get(i);
1892                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1893                // Should not happen, but we shouldn't be failing if it does
1894                if (pkgSetting == null) {
1895                    continue;
1896                }
1897                boolean install = enableApps.contains(pName);
1898                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1899                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1900                            + " for system user");
1901                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1902                }
1903            }
1904        }
1905    }
1906
1907    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1908        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1909                Context.DISPLAY_SERVICE);
1910        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1911    }
1912
1913    public PackageManagerService(Context context, Installer installer,
1914            boolean factoryTest, boolean onlyCore) {
1915        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1916                SystemClock.uptimeMillis());
1917
1918        if (mSdkVersion <= 0) {
1919            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1920        }
1921
1922        mContext = context;
1923        mFactoryTest = factoryTest;
1924        mOnlyCore = onlyCore;
1925        mMetrics = new DisplayMetrics();
1926        mSettings = new Settings(mPackages);
1927        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1928                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1929        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1930                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1931        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1932                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1933        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1934                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1935        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1936                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1937        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1938                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1939
1940        String separateProcesses = SystemProperties.get("debug.separate_processes");
1941        if (separateProcesses != null && separateProcesses.length() > 0) {
1942            if ("*".equals(separateProcesses)) {
1943                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1944                mSeparateProcesses = null;
1945                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1946            } else {
1947                mDefParseFlags = 0;
1948                mSeparateProcesses = separateProcesses.split(",");
1949                Slog.w(TAG, "Running with debug.separate_processes: "
1950                        + separateProcesses);
1951            }
1952        } else {
1953            mDefParseFlags = 0;
1954            mSeparateProcesses = null;
1955        }
1956
1957        mInstaller = installer;
1958        mPackageDexOptimizer = new PackageDexOptimizer(this);
1959        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1960
1961        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1962                FgThread.get().getLooper());
1963
1964        getDefaultDisplayMetrics(context, mMetrics);
1965
1966        SystemConfig systemConfig = SystemConfig.getInstance();
1967        mGlobalGids = systemConfig.getGlobalGids();
1968        mSystemPermissions = systemConfig.getSystemPermissions();
1969        mAvailableFeatures = systemConfig.getAvailableFeatures();
1970
1971        synchronized (mInstallLock) {
1972        // writer
1973        synchronized (mPackages) {
1974            mHandlerThread = new ServiceThread(TAG,
1975                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1976            mHandlerThread.start();
1977            mHandler = new PackageHandler(mHandlerThread.getLooper());
1978            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1979
1980            File dataDir = Environment.getDataDirectory();
1981            mAppInstallDir = new File(dataDir, "app");
1982            mAppLib32InstallDir = new File(dataDir, "app-lib");
1983            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1984            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1985            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1986
1987            sUserManager = new UserManagerService(context, this, mPackages);
1988
1989            // Propagate permission configuration in to package manager.
1990            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1991                    = systemConfig.getPermissions();
1992            for (int i=0; i<permConfig.size(); i++) {
1993                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1994                BasePermission bp = mSettings.mPermissions.get(perm.name);
1995                if (bp == null) {
1996                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1997                    mSettings.mPermissions.put(perm.name, bp);
1998                }
1999                if (perm.gids != null) {
2000                    bp.setGids(perm.gids, perm.perUser);
2001                }
2002            }
2003
2004            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2005            for (int i=0; i<libConfig.size(); i++) {
2006                mSharedLibraries.put(libConfig.keyAt(i),
2007                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2008            }
2009
2010            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2011
2012            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2013
2014            String customResolverActivity = Resources.getSystem().getString(
2015                    R.string.config_customResolverActivity);
2016            if (TextUtils.isEmpty(customResolverActivity)) {
2017                customResolverActivity = null;
2018            } else {
2019                mCustomResolverComponentName = ComponentName.unflattenFromString(
2020                        customResolverActivity);
2021            }
2022
2023            long startTime = SystemClock.uptimeMillis();
2024
2025            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2026                    startTime);
2027
2028            // Set flag to monitor and not change apk file paths when
2029            // scanning install directories.
2030            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2031
2032            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2033            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2034
2035            if (bootClassPath == null) {
2036                Slog.w(TAG, "No BOOTCLASSPATH found!");
2037            }
2038
2039            if (systemServerClassPath == null) {
2040                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2041            }
2042
2043            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2044            final String[] dexCodeInstructionSets =
2045                    getDexCodeInstructionSets(
2046                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2047
2048            /**
2049             * Ensure all external libraries have had dexopt run on them.
2050             */
2051            if (mSharedLibraries.size() > 0) {
2052                // NOTE: For now, we're compiling these system "shared libraries"
2053                // (and framework jars) into all available architectures. It's possible
2054                // to compile them only when we come across an app that uses them (there's
2055                // already logic for that in scanPackageLI) but that adds some complexity.
2056                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2057                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2058                        final String lib = libEntry.path;
2059                        if (lib == null) {
2060                            continue;
2061                        }
2062
2063                        try {
2064                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2065                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2066                                // Shared libraries do not have profiles so we perform a full
2067                                // AOT compilation.
2068                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2069                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2070                                        StorageManager.UUID_PRIVATE_INTERNAL,
2071                                        false /*useProfiles*/);
2072                            }
2073                        } catch (FileNotFoundException e) {
2074                            Slog.w(TAG, "Library not found: " + lib);
2075                        } catch (IOException | InstallerException e) {
2076                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2077                                    + e.getMessage());
2078                        }
2079                    }
2080                }
2081            }
2082
2083            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2084
2085            final VersionInfo ver = mSettings.getInternalVersion();
2086            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2087            // when upgrading from pre-M, promote system app permissions from install to runtime
2088            mPromoteSystemApps =
2089                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2090
2091            // save off the names of pre-existing system packages prior to scanning; we don't
2092            // want to automatically grant runtime permissions for new system apps
2093            if (mPromoteSystemApps) {
2094                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2095                while (pkgSettingIter.hasNext()) {
2096                    PackageSetting ps = pkgSettingIter.next();
2097                    if (isSystemApp(ps)) {
2098                        mExistingSystemPackages.add(ps.name);
2099                    }
2100                }
2101            }
2102
2103            // Collect vendor overlay packages.
2104            // (Do this before scanning any apps.)
2105            // For security and version matching reason, only consider
2106            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2107            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2108            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2109                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2110
2111            // Find base frameworks (resource packages without code).
2112            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2113                    | PackageParser.PARSE_IS_SYSTEM_DIR
2114                    | PackageParser.PARSE_IS_PRIVILEGED,
2115                    scanFlags | SCAN_NO_DEX, 0);
2116
2117            // Collected privileged system packages.
2118            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2119            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2120                    | PackageParser.PARSE_IS_SYSTEM_DIR
2121                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2122
2123            // Collect ordinary system packages.
2124            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2125            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2126                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2127
2128            // Collect all vendor packages.
2129            File vendorAppDir = new File("/vendor/app");
2130            try {
2131                vendorAppDir = vendorAppDir.getCanonicalFile();
2132            } catch (IOException e) {
2133                // failed to look up canonical path, continue with original one
2134            }
2135            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2136                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2137
2138            // Collect all OEM packages.
2139            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2140            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2141                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2142
2143            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2144            try {
2145                mInstaller.moveFiles();
2146            } catch (InstallerException e) {
2147                logCriticalInfo(Log.WARN, "Update commands failed: " + e);
2148            }
2149
2150            // Prune any system packages that no longer exist.
2151            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2152            if (!mOnlyCore) {
2153                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2154                while (psit.hasNext()) {
2155                    PackageSetting ps = psit.next();
2156
2157                    /*
2158                     * If this is not a system app, it can't be a
2159                     * disable system app.
2160                     */
2161                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2162                        continue;
2163                    }
2164
2165                    /*
2166                     * If the package is scanned, it's not erased.
2167                     */
2168                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2169                    if (scannedPkg != null) {
2170                        /*
2171                         * If the system app is both scanned and in the
2172                         * disabled packages list, then it must have been
2173                         * added via OTA. Remove it from the currently
2174                         * scanned package so the previously user-installed
2175                         * application can be scanned.
2176                         */
2177                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2178                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2179                                    + ps.name + "; removing system app.  Last known codePath="
2180                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2181                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2182                                    + scannedPkg.mVersionCode);
2183                            removePackageLI(ps, true);
2184                            mExpectingBetter.put(ps.name, ps.codePath);
2185                        }
2186
2187                        continue;
2188                    }
2189
2190                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2191                        psit.remove();
2192                        logCriticalInfo(Log.WARN, "System package " + ps.name
2193                                + " no longer exists; wiping its data");
2194                        removeDataDirsLI(null, ps.name);
2195                    } else {
2196                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2197                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2198                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2199                        }
2200                    }
2201                }
2202            }
2203
2204            //look for any incomplete package installations
2205            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2206            //clean up list
2207            for(int i = 0; i < deletePkgsList.size(); i++) {
2208                //clean up here
2209                cleanupInstallFailedPackage(deletePkgsList.get(i));
2210            }
2211            //delete tmp files
2212            deleteTempPackageFiles();
2213
2214            // Remove any shared userIDs that have no associated packages
2215            mSettings.pruneSharedUsersLPw();
2216
2217            if (!mOnlyCore) {
2218                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2219                        SystemClock.uptimeMillis());
2220                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2221
2222                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2223                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2224
2225                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2226                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2227
2228                /**
2229                 * Remove disable package settings for any updated system
2230                 * apps that were removed via an OTA. If they're not a
2231                 * previously-updated app, remove them completely.
2232                 * Otherwise, just revoke their system-level permissions.
2233                 */
2234                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2235                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2236                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2237
2238                    String msg;
2239                    if (deletedPkg == null) {
2240                        msg = "Updated system package " + deletedAppName
2241                                + " no longer exists; wiping its data";
2242                        removeDataDirsLI(null, deletedAppName);
2243                    } else {
2244                        msg = "Updated system app + " + deletedAppName
2245                                + " no longer present; removing system privileges for "
2246                                + deletedAppName;
2247
2248                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2249
2250                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2251                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2252                    }
2253                    logCriticalInfo(Log.WARN, msg);
2254                }
2255
2256                /**
2257                 * Make sure all system apps that we expected to appear on
2258                 * the userdata partition actually showed up. If they never
2259                 * appeared, crawl back and revive the system version.
2260                 */
2261                for (int i = 0; i < mExpectingBetter.size(); i++) {
2262                    final String packageName = mExpectingBetter.keyAt(i);
2263                    if (!mPackages.containsKey(packageName)) {
2264                        final File scanFile = mExpectingBetter.valueAt(i);
2265
2266                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2267                                + " but never showed up; reverting to system");
2268
2269                        final int reparseFlags;
2270                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2271                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2272                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2273                                    | PackageParser.PARSE_IS_PRIVILEGED;
2274                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2275                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2276                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2277                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2278                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2279                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2280                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2281                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2282                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2283                        } else {
2284                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2285                            continue;
2286                        }
2287
2288                        mSettings.enableSystemPackageLPw(packageName);
2289
2290                        try {
2291                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2292                        } catch (PackageManagerException e) {
2293                            Slog.e(TAG, "Failed to parse original system package: "
2294                                    + e.getMessage());
2295                        }
2296                    }
2297                }
2298            }
2299            mExpectingBetter.clear();
2300
2301            // Now that we know all of the shared libraries, update all clients to have
2302            // the correct library paths.
2303            updateAllSharedLibrariesLPw();
2304
2305            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2306                // NOTE: We ignore potential failures here during a system scan (like
2307                // the rest of the commands above) because there's precious little we
2308                // can do about it. A settings error is reported, though.
2309                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2310                        false /* boot complete */);
2311            }
2312
2313            // Now that we know all the packages we are keeping,
2314            // read and update their last usage times.
2315            mPackageUsage.readLP();
2316
2317            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2318                    SystemClock.uptimeMillis());
2319            Slog.i(TAG, "Time to scan packages: "
2320                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2321                    + " seconds");
2322
2323            // If the platform SDK has changed since the last time we booted,
2324            // we need to re-grant app permission to catch any new ones that
2325            // appear.  This is really a hack, and means that apps can in some
2326            // cases get permissions that the user didn't initially explicitly
2327            // allow...  it would be nice to have some better way to handle
2328            // this situation.
2329            int updateFlags = UPDATE_PERMISSIONS_ALL;
2330            if (ver.sdkVersion != mSdkVersion) {
2331                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2332                        + mSdkVersion + "; regranting permissions for internal storage");
2333                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2334            }
2335            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2336            ver.sdkVersion = mSdkVersion;
2337
2338            // If this is the first boot or an update from pre-M, and it is a normal
2339            // boot, then we need to initialize the default preferred apps across
2340            // all defined users.
2341            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2342                for (UserInfo user : sUserManager.getUsers(true)) {
2343                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2344                    applyFactoryDefaultBrowserLPw(user.id);
2345                    primeDomainVerificationsLPw(user.id);
2346                }
2347            }
2348
2349            // If this is first boot after an OTA, and a normal boot, then
2350            // we need to clear code cache directories.
2351            if (mIsUpgrade && !onlyCore) {
2352                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2353                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2354                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2355                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2356                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2357                    }
2358                }
2359                ver.fingerprint = Build.FINGERPRINT;
2360            }
2361
2362            checkDefaultBrowser();
2363
2364            // clear only after permissions and other defaults have been updated
2365            mExistingSystemPackages.clear();
2366            mPromoteSystemApps = false;
2367
2368            // All the changes are done during package scanning.
2369            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2370
2371            // can downgrade to reader
2372            mSettings.writeLPr();
2373
2374            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2375                    SystemClock.uptimeMillis());
2376
2377            if (!mOnlyCore) {
2378                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2379                mRequiredInstallerPackage = getRequiredInstallerLPr();
2380                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2381                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2382                        mIntentFilterVerifierComponent);
2383            } else {
2384                mRequiredVerifierPackage = null;
2385                mRequiredInstallerPackage = null;
2386                mIntentFilterVerifierComponent = null;
2387                mIntentFilterVerifier = null;
2388            }
2389
2390            mInstallerService = new PackageInstallerService(context, this);
2391
2392            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2393            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2394            // both the installer and resolver must be present to enable ephemeral
2395            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2396                if (DEBUG_EPHEMERAL) {
2397                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2398                            + " installer:" + ephemeralInstallerComponent);
2399                }
2400                mEphemeralResolverComponent = ephemeralResolverComponent;
2401                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2402                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2403                mEphemeralResolverConnection =
2404                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2405            } else {
2406                if (DEBUG_EPHEMERAL) {
2407                    final String missingComponent =
2408                            (ephemeralResolverComponent == null)
2409                            ? (ephemeralInstallerComponent == null)
2410                                    ? "resolver and installer"
2411                                    : "resolver"
2412                            : "installer";
2413                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2414                }
2415                mEphemeralResolverComponent = null;
2416                mEphemeralInstallerComponent = null;
2417                mEphemeralResolverConnection = null;
2418            }
2419
2420            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2421        } // synchronized (mPackages)
2422        } // synchronized (mInstallLock)
2423
2424        // Now after opening every single application zip, make sure they
2425        // are all flushed.  Not really needed, but keeps things nice and
2426        // tidy.
2427        Runtime.getRuntime().gc();
2428
2429        // The initial scanning above does many calls into installd while
2430        // holding the mPackages lock, but we're mostly interested in yelling
2431        // once we have a booted system.
2432        mInstaller.setWarnIfHeld(mPackages);
2433
2434        // Expose private service for system components to use.
2435        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2436    }
2437
2438    @Override
2439    public boolean isFirstBoot() {
2440        return !mRestoredSettings;
2441    }
2442
2443    @Override
2444    public boolean isOnlyCoreApps() {
2445        return mOnlyCore;
2446    }
2447
2448    @Override
2449    public boolean isUpgrade() {
2450        return mIsUpgrade;
2451    }
2452
2453    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2454        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2455
2456        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2457                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2458        if (matches.size() == 1) {
2459            return matches.get(0).getComponentInfo().packageName;
2460        } else {
2461            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2462            return null;
2463        }
2464    }
2465
2466    private @NonNull String getRequiredInstallerLPr() {
2467        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2468        intent.addCategory(Intent.CATEGORY_DEFAULT);
2469        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2470
2471        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2472                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2473        if (matches.size() == 1) {
2474            return matches.get(0).getComponentInfo().packageName;
2475        } else {
2476            throw new RuntimeException("There must be exactly one installer; found " + matches);
2477        }
2478    }
2479
2480    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2481        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2482
2483        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2484                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2485        ResolveInfo best = null;
2486        final int N = matches.size();
2487        for (int i = 0; i < N; i++) {
2488            final ResolveInfo cur = matches.get(i);
2489            final String packageName = cur.getComponentInfo().packageName;
2490            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2491                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2492                continue;
2493            }
2494
2495            if (best == null || cur.priority > best.priority) {
2496                best = cur;
2497            }
2498        }
2499
2500        if (best != null) {
2501            return best.getComponentInfo().getComponentName();
2502        } else {
2503            throw new RuntimeException("There must be at least one intent filter verifier");
2504        }
2505    }
2506
2507    private @Nullable ComponentName getEphemeralResolverLPr() {
2508        final String[] packageArray =
2509                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2510        if (packageArray.length == 0) {
2511            if (DEBUG_EPHEMERAL) {
2512                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2513            }
2514            return null;
2515        }
2516
2517        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2518        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2519                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2520
2521        final int N = resolvers.size();
2522        if (N == 0) {
2523            if (DEBUG_EPHEMERAL) {
2524                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2525            }
2526            return null;
2527        }
2528
2529        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2530        for (int i = 0; i < N; i++) {
2531            final ResolveInfo info = resolvers.get(i);
2532
2533            if (info.serviceInfo == null) {
2534                continue;
2535            }
2536
2537            final String packageName = info.serviceInfo.packageName;
2538            if (!possiblePackages.contains(packageName)) {
2539                if (DEBUG_EPHEMERAL) {
2540                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2541                            + " pkg: " + packageName + ", info:" + info);
2542                }
2543                continue;
2544            }
2545
2546            if (DEBUG_EPHEMERAL) {
2547                Slog.v(TAG, "Ephemeral resolver found;"
2548                        + " pkg: " + packageName + ", info:" + info);
2549            }
2550            return new ComponentName(packageName, info.serviceInfo.name);
2551        }
2552        if (DEBUG_EPHEMERAL) {
2553            Slog.v(TAG, "Ephemeral resolver NOT found");
2554        }
2555        return null;
2556    }
2557
2558    private @Nullable ComponentName getEphemeralInstallerLPr() {
2559        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2560        intent.addCategory(Intent.CATEGORY_DEFAULT);
2561        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2562
2563        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2564                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2565        if (matches.size() == 0) {
2566            return null;
2567        } else if (matches.size() == 1) {
2568            return matches.get(0).getComponentInfo().getComponentName();
2569        } else {
2570            throw new RuntimeException(
2571                    "There must be at most one ephemeral installer; found " + matches);
2572        }
2573    }
2574
2575    private void primeDomainVerificationsLPw(int userId) {
2576        if (DEBUG_DOMAIN_VERIFICATION) {
2577            Slog.d(TAG, "Priming domain verifications in user " + userId);
2578        }
2579
2580        SystemConfig systemConfig = SystemConfig.getInstance();
2581        ArraySet<String> packages = systemConfig.getLinkedApps();
2582        ArraySet<String> domains = new ArraySet<String>();
2583
2584        for (String packageName : packages) {
2585            PackageParser.Package pkg = mPackages.get(packageName);
2586            if (pkg != null) {
2587                if (!pkg.isSystemApp()) {
2588                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2589                    continue;
2590                }
2591
2592                domains.clear();
2593                for (PackageParser.Activity a : pkg.activities) {
2594                    for (ActivityIntentInfo filter : a.intents) {
2595                        if (hasValidDomains(filter)) {
2596                            domains.addAll(filter.getHostsList());
2597                        }
2598                    }
2599                }
2600
2601                if (domains.size() > 0) {
2602                    if (DEBUG_DOMAIN_VERIFICATION) {
2603                        Slog.v(TAG, "      + " + packageName);
2604                    }
2605                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2606                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2607                    // and then 'always' in the per-user state actually used for intent resolution.
2608                    final IntentFilterVerificationInfo ivi;
2609                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2610                            new ArrayList<String>(domains));
2611                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2612                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2613                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2614                } else {
2615                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2616                            + "' does not handle web links");
2617                }
2618            } else {
2619                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2620            }
2621        }
2622
2623        scheduleWritePackageRestrictionsLocked(userId);
2624        scheduleWriteSettingsLocked();
2625    }
2626
2627    private void applyFactoryDefaultBrowserLPw(int userId) {
2628        // The default browser app's package name is stored in a string resource,
2629        // with a product-specific overlay used for vendor customization.
2630        String browserPkg = mContext.getResources().getString(
2631                com.android.internal.R.string.default_browser);
2632        if (!TextUtils.isEmpty(browserPkg)) {
2633            // non-empty string => required to be a known package
2634            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2635            if (ps == null) {
2636                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2637                browserPkg = null;
2638            } else {
2639                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2640            }
2641        }
2642
2643        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2644        // default.  If there's more than one, just leave everything alone.
2645        if (browserPkg == null) {
2646            calculateDefaultBrowserLPw(userId);
2647        }
2648    }
2649
2650    private void calculateDefaultBrowserLPw(int userId) {
2651        List<String> allBrowsers = resolveAllBrowserApps(userId);
2652        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2653        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2654    }
2655
2656    private List<String> resolveAllBrowserApps(int userId) {
2657        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2658        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2659                PackageManager.MATCH_ALL, userId);
2660
2661        final int count = list.size();
2662        List<String> result = new ArrayList<String>(count);
2663        for (int i=0; i<count; i++) {
2664            ResolveInfo info = list.get(i);
2665            if (info.activityInfo == null
2666                    || !info.handleAllWebDataURI
2667                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2668                    || result.contains(info.activityInfo.packageName)) {
2669                continue;
2670            }
2671            result.add(info.activityInfo.packageName);
2672        }
2673
2674        return result;
2675    }
2676
2677    private boolean packageIsBrowser(String packageName, int userId) {
2678        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2679                PackageManager.MATCH_ALL, userId);
2680        final int N = list.size();
2681        for (int i = 0; i < N; i++) {
2682            ResolveInfo info = list.get(i);
2683            if (packageName.equals(info.activityInfo.packageName)) {
2684                return true;
2685            }
2686        }
2687        return false;
2688    }
2689
2690    private void checkDefaultBrowser() {
2691        final int myUserId = UserHandle.myUserId();
2692        final String packageName = getDefaultBrowserPackageName(myUserId);
2693        if (packageName != null) {
2694            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2695            if (info == null) {
2696                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2697                synchronized (mPackages) {
2698                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2699                }
2700            }
2701        }
2702    }
2703
2704    @Override
2705    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2706            throws RemoteException {
2707        try {
2708            return super.onTransact(code, data, reply, flags);
2709        } catch (RuntimeException e) {
2710            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2711                Slog.wtf(TAG, "Package Manager Crash", e);
2712            }
2713            throw e;
2714        }
2715    }
2716
2717    void cleanupInstallFailedPackage(PackageSetting ps) {
2718        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2719
2720        removeDataDirsLI(ps.volumeUuid, ps.name);
2721        if (ps.codePath != null) {
2722            removeCodePathLI(ps.codePath);
2723        }
2724        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2725            if (ps.resourcePath.isDirectory()) {
2726                FileUtils.deleteContents(ps.resourcePath);
2727            }
2728            ps.resourcePath.delete();
2729        }
2730        mSettings.removePackageLPw(ps.name);
2731    }
2732
2733    static int[] appendInts(int[] cur, int[] add) {
2734        if (add == null) return cur;
2735        if (cur == null) return add;
2736        final int N = add.length;
2737        for (int i=0; i<N; i++) {
2738            cur = appendInt(cur, add[i]);
2739        }
2740        return cur;
2741    }
2742
2743    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2744        if (!sUserManager.exists(userId)) return null;
2745        final PackageSetting ps = (PackageSetting) p.mExtras;
2746        if (ps == null) {
2747            return null;
2748        }
2749
2750        final PermissionsState permissionsState = ps.getPermissionsState();
2751
2752        final int[] gids = permissionsState.computeGids(userId);
2753        final Set<String> permissions = permissionsState.getPermissions(userId);
2754        final PackageUserState state = ps.readUserState(userId);
2755
2756        return PackageParser.generatePackageInfo(p, gids, flags,
2757                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2758    }
2759
2760    @Override
2761    public void checkPackageStartable(String packageName, int userId) {
2762        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2763
2764        synchronized (mPackages) {
2765            final PackageSetting ps = mSettings.mPackages.get(packageName);
2766            if (ps == null) {
2767                throw new SecurityException("Package " + packageName + " was not found!");
2768            }
2769
2770            if (ps.frozen) {
2771                throw new SecurityException("Package " + packageName + " is currently frozen!");
2772            }
2773
2774            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2775                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2776                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2777            }
2778        }
2779    }
2780
2781    @Override
2782    public boolean isPackageAvailable(String packageName, int userId) {
2783        if (!sUserManager.exists(userId)) return false;
2784        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2785        synchronized (mPackages) {
2786            PackageParser.Package p = mPackages.get(packageName);
2787            if (p != null) {
2788                final PackageSetting ps = (PackageSetting) p.mExtras;
2789                if (ps != null) {
2790                    final PackageUserState state = ps.readUserState(userId);
2791                    if (state != null) {
2792                        return PackageParser.isAvailable(state);
2793                    }
2794                }
2795            }
2796        }
2797        return false;
2798    }
2799
2800    @Override
2801    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2802        if (!sUserManager.exists(userId)) return null;
2803        flags = updateFlagsForPackage(flags, userId, packageName);
2804        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2805        // reader
2806        synchronized (mPackages) {
2807            PackageParser.Package p = mPackages.get(packageName);
2808            if (DEBUG_PACKAGE_INFO)
2809                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2810            if (p != null) {
2811                return generatePackageInfo(p, flags, userId);
2812            }
2813            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2814                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2815            }
2816        }
2817        return null;
2818    }
2819
2820    @Override
2821    public String[] currentToCanonicalPackageNames(String[] names) {
2822        String[] out = new String[names.length];
2823        // reader
2824        synchronized (mPackages) {
2825            for (int i=names.length-1; i>=0; i--) {
2826                PackageSetting ps = mSettings.mPackages.get(names[i]);
2827                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2828            }
2829        }
2830        return out;
2831    }
2832
2833    @Override
2834    public String[] canonicalToCurrentPackageNames(String[] names) {
2835        String[] out = new String[names.length];
2836        // reader
2837        synchronized (mPackages) {
2838            for (int i=names.length-1; i>=0; i--) {
2839                String cur = mSettings.mRenamedPackages.get(names[i]);
2840                out[i] = cur != null ? cur : names[i];
2841            }
2842        }
2843        return out;
2844    }
2845
2846    @Override
2847    public int getPackageUid(String packageName, int flags, int userId) {
2848        if (!sUserManager.exists(userId)) return -1;
2849        flags = updateFlagsForPackage(flags, userId, packageName);
2850        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2851
2852        // reader
2853        synchronized (mPackages) {
2854            final PackageParser.Package p = mPackages.get(packageName);
2855            if (p != null && p.isMatch(flags)) {
2856                return UserHandle.getUid(userId, p.applicationInfo.uid);
2857            }
2858            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2859                final PackageSetting ps = mSettings.mPackages.get(packageName);
2860                if (ps != null && ps.isMatch(flags)) {
2861                    return UserHandle.getUid(userId, ps.appId);
2862                }
2863            }
2864        }
2865
2866        return -1;
2867    }
2868
2869    @Override
2870    public int[] getPackageGids(String packageName, int flags, int userId) {
2871        if (!sUserManager.exists(userId)) return null;
2872        flags = updateFlagsForPackage(flags, userId, packageName);
2873        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2874                "getPackageGids");
2875
2876        // reader
2877        synchronized (mPackages) {
2878            final PackageParser.Package p = mPackages.get(packageName);
2879            if (p != null && p.isMatch(flags)) {
2880                PackageSetting ps = (PackageSetting) p.mExtras;
2881                return ps.getPermissionsState().computeGids(userId);
2882            }
2883            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2884                final PackageSetting ps = mSettings.mPackages.get(packageName);
2885                if (ps != null && ps.isMatch(flags)) {
2886                    return ps.getPermissionsState().computeGids(userId);
2887                }
2888            }
2889        }
2890
2891        return null;
2892    }
2893
2894    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2895        if (bp.perm != null) {
2896            return PackageParser.generatePermissionInfo(bp.perm, flags);
2897        }
2898        PermissionInfo pi = new PermissionInfo();
2899        pi.name = bp.name;
2900        pi.packageName = bp.sourcePackage;
2901        pi.nonLocalizedLabel = bp.name;
2902        pi.protectionLevel = bp.protectionLevel;
2903        return pi;
2904    }
2905
2906    @Override
2907    public PermissionInfo getPermissionInfo(String name, int flags) {
2908        // reader
2909        synchronized (mPackages) {
2910            final BasePermission p = mSettings.mPermissions.get(name);
2911            if (p != null) {
2912                return generatePermissionInfo(p, flags);
2913            }
2914            return null;
2915        }
2916    }
2917
2918    @Override
2919    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2920        // reader
2921        synchronized (mPackages) {
2922            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2923            for (BasePermission p : mSettings.mPermissions.values()) {
2924                if (group == null) {
2925                    if (p.perm == null || p.perm.info.group == null) {
2926                        out.add(generatePermissionInfo(p, flags));
2927                    }
2928                } else {
2929                    if (p.perm != null && group.equals(p.perm.info.group)) {
2930                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2931                    }
2932                }
2933            }
2934
2935            if (out.size() > 0) {
2936                return out;
2937            }
2938            return mPermissionGroups.containsKey(group) ? out : null;
2939        }
2940    }
2941
2942    @Override
2943    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2944        // reader
2945        synchronized (mPackages) {
2946            return PackageParser.generatePermissionGroupInfo(
2947                    mPermissionGroups.get(name), flags);
2948        }
2949    }
2950
2951    @Override
2952    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2953        // reader
2954        synchronized (mPackages) {
2955            final int N = mPermissionGroups.size();
2956            ArrayList<PermissionGroupInfo> out
2957                    = new ArrayList<PermissionGroupInfo>(N);
2958            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2959                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2960            }
2961            return out;
2962        }
2963    }
2964
2965    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2966            int userId) {
2967        if (!sUserManager.exists(userId)) return null;
2968        PackageSetting ps = mSettings.mPackages.get(packageName);
2969        if (ps != null) {
2970            if (ps.pkg == null) {
2971                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2972                        flags, userId);
2973                if (pInfo != null) {
2974                    return pInfo.applicationInfo;
2975                }
2976                return null;
2977            }
2978            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2979                    ps.readUserState(userId), userId);
2980        }
2981        return null;
2982    }
2983
2984    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2985            int userId) {
2986        if (!sUserManager.exists(userId)) return null;
2987        PackageSetting ps = mSettings.mPackages.get(packageName);
2988        if (ps != null) {
2989            PackageParser.Package pkg = ps.pkg;
2990            if (pkg == null) {
2991                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
2992                    return null;
2993                }
2994                // Only data remains, so we aren't worried about code paths
2995                pkg = new PackageParser.Package(packageName);
2996                pkg.applicationInfo.packageName = packageName;
2997                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2998                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2999                pkg.applicationInfo.uid = ps.appId;
3000                pkg.applicationInfo.initForUser(userId);
3001                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3002                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3003            }
3004            return generatePackageInfo(pkg, flags, userId);
3005        }
3006        return null;
3007    }
3008
3009    @Override
3010    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3011        if (!sUserManager.exists(userId)) return null;
3012        flags = updateFlagsForApplication(flags, userId, packageName);
3013        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3014        // writer
3015        synchronized (mPackages) {
3016            PackageParser.Package p = mPackages.get(packageName);
3017            if (DEBUG_PACKAGE_INFO) Log.v(
3018                    TAG, "getApplicationInfo " + packageName
3019                    + ": " + p);
3020            if (p != null) {
3021                PackageSetting ps = mSettings.mPackages.get(packageName);
3022                if (ps == null) return null;
3023                // Note: isEnabledLP() does not apply here - always return info
3024                return PackageParser.generateApplicationInfo(
3025                        p, flags, ps.readUserState(userId), userId);
3026            }
3027            if ("android".equals(packageName)||"system".equals(packageName)) {
3028                return mAndroidApplication;
3029            }
3030            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3031                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3032            }
3033        }
3034        return null;
3035    }
3036
3037    @Override
3038    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3039            final IPackageDataObserver observer) {
3040        mContext.enforceCallingOrSelfPermission(
3041                android.Manifest.permission.CLEAR_APP_CACHE, null);
3042        // Queue up an async operation since clearing cache may take a little while.
3043        mHandler.post(new Runnable() {
3044            public void run() {
3045                mHandler.removeCallbacks(this);
3046                boolean success = true;
3047                synchronized (mInstallLock) {
3048                    try {
3049                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3050                    } catch (InstallerException e) {
3051                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3052                        success = false;
3053                    }
3054                }
3055                if (observer != null) {
3056                    try {
3057                        observer.onRemoveCompleted(null, success);
3058                    } catch (RemoteException e) {
3059                        Slog.w(TAG, "RemoveException when invoking call back");
3060                    }
3061                }
3062            }
3063        });
3064    }
3065
3066    @Override
3067    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3068            final IntentSender pi) {
3069        mContext.enforceCallingOrSelfPermission(
3070                android.Manifest.permission.CLEAR_APP_CACHE, null);
3071        // Queue up an async operation since clearing cache may take a little while.
3072        mHandler.post(new Runnable() {
3073            public void run() {
3074                mHandler.removeCallbacks(this);
3075                boolean success = true;
3076                synchronized (mInstallLock) {
3077                    try {
3078                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3079                    } catch (InstallerException e) {
3080                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3081                        success = false;
3082                    }
3083                }
3084                if(pi != null) {
3085                    try {
3086                        // Callback via pending intent
3087                        int code = success ? 1 : 0;
3088                        pi.sendIntent(null, code, null,
3089                                null, null);
3090                    } catch (SendIntentException e1) {
3091                        Slog.i(TAG, "Failed to send pending intent");
3092                    }
3093                }
3094            }
3095        });
3096    }
3097
3098    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3099        synchronized (mInstallLock) {
3100            try {
3101                mInstaller.freeCache(volumeUuid, freeStorageSize);
3102            } catch (InstallerException e) {
3103                throw new IOException("Failed to free enough space", e);
3104            }
3105        }
3106    }
3107
3108    /**
3109     * Return if the user key is currently unlocked.
3110     */
3111    private boolean isUserKeyUnlocked(int userId) {
3112        if (StorageManager.isFileBasedEncryptionEnabled()) {
3113            final IMountService mount = IMountService.Stub
3114                    .asInterface(ServiceManager.getService("mount"));
3115            if (mount == null) {
3116                Slog.w(TAG, "Early during boot, assuming locked");
3117                return false;
3118            }
3119            final long token = Binder.clearCallingIdentity();
3120            try {
3121                return mount.isUserKeyUnlocked(userId);
3122            } catch (RemoteException e) {
3123                throw e.rethrowAsRuntimeException();
3124            } finally {
3125                Binder.restoreCallingIdentity(token);
3126            }
3127        } else {
3128            return true;
3129        }
3130    }
3131
3132    /**
3133     * Update given flags based on encryption status of current user.
3134     */
3135    private int updateFlags(int flags, int userId) {
3136        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3137                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3138            // Caller expressed an explicit opinion about what encryption
3139            // aware/unaware components they want to see, so fall through and
3140            // give them what they want
3141        } else {
3142            // Caller expressed no opinion, so match based on user state
3143            if (isUserKeyUnlocked(userId)) {
3144                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3145            } else {
3146                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3147            }
3148        }
3149
3150        // Safe mode means we should ignore any third-party apps
3151        if (mSafeMode) {
3152            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3153        }
3154
3155        return flags;
3156    }
3157
3158    /**
3159     * Update given flags when being used to request {@link PackageInfo}.
3160     */
3161    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3162        boolean triaged = true;
3163        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3164                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3165            // Caller is asking for component details, so they'd better be
3166            // asking for specific encryption matching behavior, or be triaged
3167            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3168                    | PackageManager.MATCH_ENCRYPTION_AWARE
3169                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3170                triaged = false;
3171            }
3172        }
3173        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3174                | PackageManager.MATCH_SYSTEM_ONLY
3175                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3176            triaged = false;
3177        }
3178        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3179            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3180                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3181        }
3182        return updateFlags(flags, userId);
3183    }
3184
3185    /**
3186     * Update given flags when being used to request {@link ApplicationInfo}.
3187     */
3188    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3189        return updateFlagsForPackage(flags, userId, cookie);
3190    }
3191
3192    /**
3193     * Update given flags when being used to request {@link ComponentInfo}.
3194     */
3195    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3196        if (cookie instanceof Intent) {
3197            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3198                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3199            }
3200        }
3201
3202        boolean triaged = true;
3203        // Caller is asking for component details, so they'd better be
3204        // asking for specific encryption matching behavior, or be triaged
3205        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3206                | PackageManager.MATCH_ENCRYPTION_AWARE
3207                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3208            triaged = false;
3209        }
3210        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3211            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3212                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3213        }
3214        return updateFlags(flags, userId);
3215    }
3216
3217    /**
3218     * Update given flags when being used to request {@link ResolveInfo}.
3219     */
3220    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3221        return updateFlagsForComponent(flags, userId, cookie);
3222    }
3223
3224    @Override
3225    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3226        if (!sUserManager.exists(userId)) return null;
3227        flags = updateFlagsForComponent(flags, userId, component);
3228        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3229        synchronized (mPackages) {
3230            PackageParser.Activity a = mActivities.mActivities.get(component);
3231
3232            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3233            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3234                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3235                if (ps == null) return null;
3236                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3237                        userId);
3238            }
3239            if (mResolveComponentName.equals(component)) {
3240                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3241                        new PackageUserState(), userId);
3242            }
3243        }
3244        return null;
3245    }
3246
3247    @Override
3248    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3249            String resolvedType) {
3250        synchronized (mPackages) {
3251            if (component.equals(mResolveComponentName)) {
3252                // The resolver supports EVERYTHING!
3253                return true;
3254            }
3255            PackageParser.Activity a = mActivities.mActivities.get(component);
3256            if (a == null) {
3257                return false;
3258            }
3259            for (int i=0; i<a.intents.size(); i++) {
3260                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3261                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3262                    return true;
3263                }
3264            }
3265            return false;
3266        }
3267    }
3268
3269    @Override
3270    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3271        if (!sUserManager.exists(userId)) return null;
3272        flags = updateFlagsForComponent(flags, userId, component);
3273        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3274        synchronized (mPackages) {
3275            PackageParser.Activity a = mReceivers.mActivities.get(component);
3276            if (DEBUG_PACKAGE_INFO) Log.v(
3277                TAG, "getReceiverInfo " + component + ": " + a);
3278            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3279                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3280                if (ps == null) return null;
3281                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3282                        userId);
3283            }
3284        }
3285        return null;
3286    }
3287
3288    @Override
3289    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3290        if (!sUserManager.exists(userId)) return null;
3291        flags = updateFlagsForComponent(flags, userId, component);
3292        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3293        synchronized (mPackages) {
3294            PackageParser.Service s = mServices.mServices.get(component);
3295            if (DEBUG_PACKAGE_INFO) Log.v(
3296                TAG, "getServiceInfo " + component + ": " + s);
3297            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3298                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3299                if (ps == null) return null;
3300                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3301                        userId);
3302            }
3303        }
3304        return null;
3305    }
3306
3307    @Override
3308    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3309        if (!sUserManager.exists(userId)) return null;
3310        flags = updateFlagsForComponent(flags, userId, component);
3311        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3312        synchronized (mPackages) {
3313            PackageParser.Provider p = mProviders.mProviders.get(component);
3314            if (DEBUG_PACKAGE_INFO) Log.v(
3315                TAG, "getProviderInfo " + component + ": " + p);
3316            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3317                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3318                if (ps == null) return null;
3319                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3320                        userId);
3321            }
3322        }
3323        return null;
3324    }
3325
3326    @Override
3327    public String[] getSystemSharedLibraryNames() {
3328        Set<String> libSet;
3329        synchronized (mPackages) {
3330            libSet = mSharedLibraries.keySet();
3331            int size = libSet.size();
3332            if (size > 0) {
3333                String[] libs = new String[size];
3334                libSet.toArray(libs);
3335                return libs;
3336            }
3337        }
3338        return null;
3339    }
3340
3341    /**
3342     * @hide
3343     */
3344    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3345        synchronized (mPackages) {
3346            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3347            if (lib != null && lib.apk != null) {
3348                return mPackages.get(lib.apk);
3349            }
3350        }
3351        return null;
3352    }
3353
3354    @Override
3355    public FeatureInfo[] getSystemAvailableFeatures() {
3356        Collection<FeatureInfo> featSet;
3357        synchronized (mPackages) {
3358            featSet = mAvailableFeatures.values();
3359            int size = featSet.size();
3360            if (size > 0) {
3361                FeatureInfo[] features = new FeatureInfo[size+1];
3362                featSet.toArray(features);
3363                FeatureInfo fi = new FeatureInfo();
3364                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3365                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3366                features[size] = fi;
3367                return features;
3368            }
3369        }
3370        return null;
3371    }
3372
3373    @Override
3374    public boolean hasSystemFeature(String name) {
3375        synchronized (mPackages) {
3376            return mAvailableFeatures.containsKey(name);
3377        }
3378    }
3379
3380    @Override
3381    public int checkPermission(String permName, String pkgName, int userId) {
3382        if (!sUserManager.exists(userId)) {
3383            return PackageManager.PERMISSION_DENIED;
3384        }
3385
3386        synchronized (mPackages) {
3387            final PackageParser.Package p = mPackages.get(pkgName);
3388            if (p != null && p.mExtras != null) {
3389                final PackageSetting ps = (PackageSetting) p.mExtras;
3390                final PermissionsState permissionsState = ps.getPermissionsState();
3391                if (permissionsState.hasPermission(permName, userId)) {
3392                    return PackageManager.PERMISSION_GRANTED;
3393                }
3394                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3395                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3396                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3397                    return PackageManager.PERMISSION_GRANTED;
3398                }
3399            }
3400        }
3401
3402        return PackageManager.PERMISSION_DENIED;
3403    }
3404
3405    @Override
3406    public int checkUidPermission(String permName, int uid) {
3407        final int userId = UserHandle.getUserId(uid);
3408
3409        if (!sUserManager.exists(userId)) {
3410            return PackageManager.PERMISSION_DENIED;
3411        }
3412
3413        synchronized (mPackages) {
3414            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3415            if (obj != null) {
3416                final SettingBase ps = (SettingBase) obj;
3417                final PermissionsState permissionsState = ps.getPermissionsState();
3418                if (permissionsState.hasPermission(permName, userId)) {
3419                    return PackageManager.PERMISSION_GRANTED;
3420                }
3421                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3422                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3423                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3424                    return PackageManager.PERMISSION_GRANTED;
3425                }
3426            } else {
3427                ArraySet<String> perms = mSystemPermissions.get(uid);
3428                if (perms != null) {
3429                    if (perms.contains(permName)) {
3430                        return PackageManager.PERMISSION_GRANTED;
3431                    }
3432                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3433                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3434                        return PackageManager.PERMISSION_GRANTED;
3435                    }
3436                }
3437            }
3438        }
3439
3440        return PackageManager.PERMISSION_DENIED;
3441    }
3442
3443    @Override
3444    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3445        if (UserHandle.getCallingUserId() != userId) {
3446            mContext.enforceCallingPermission(
3447                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3448                    "isPermissionRevokedByPolicy for user " + userId);
3449        }
3450
3451        if (checkPermission(permission, packageName, userId)
3452                == PackageManager.PERMISSION_GRANTED) {
3453            return false;
3454        }
3455
3456        final long identity = Binder.clearCallingIdentity();
3457        try {
3458            final int flags = getPermissionFlags(permission, packageName, userId);
3459            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3460        } finally {
3461            Binder.restoreCallingIdentity(identity);
3462        }
3463    }
3464
3465    @Override
3466    public String getPermissionControllerPackageName() {
3467        synchronized (mPackages) {
3468            return mRequiredInstallerPackage;
3469        }
3470    }
3471
3472    /**
3473     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3474     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3475     * @param checkShell TODO(yamasani):
3476     * @param message the message to log on security exception
3477     */
3478    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3479            boolean checkShell, String message) {
3480        if (userId < 0) {
3481            throw new IllegalArgumentException("Invalid userId " + userId);
3482        }
3483        if (checkShell) {
3484            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3485        }
3486        if (userId == UserHandle.getUserId(callingUid)) return;
3487        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3488            if (requireFullPermission) {
3489                mContext.enforceCallingOrSelfPermission(
3490                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3491            } else {
3492                try {
3493                    mContext.enforceCallingOrSelfPermission(
3494                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3495                } catch (SecurityException se) {
3496                    mContext.enforceCallingOrSelfPermission(
3497                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3498                }
3499            }
3500        }
3501    }
3502
3503    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3504        if (callingUid == Process.SHELL_UID) {
3505            if (userHandle >= 0
3506                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3507                throw new SecurityException("Shell does not have permission to access user "
3508                        + userHandle);
3509            } else if (userHandle < 0) {
3510                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3511                        + Debug.getCallers(3));
3512            }
3513        }
3514    }
3515
3516    private BasePermission findPermissionTreeLP(String permName) {
3517        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3518            if (permName.startsWith(bp.name) &&
3519                    permName.length() > bp.name.length() &&
3520                    permName.charAt(bp.name.length()) == '.') {
3521                return bp;
3522            }
3523        }
3524        return null;
3525    }
3526
3527    private BasePermission checkPermissionTreeLP(String permName) {
3528        if (permName != null) {
3529            BasePermission bp = findPermissionTreeLP(permName);
3530            if (bp != null) {
3531                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3532                    return bp;
3533                }
3534                throw new SecurityException("Calling uid "
3535                        + Binder.getCallingUid()
3536                        + " is not allowed to add to permission tree "
3537                        + bp.name + " owned by uid " + bp.uid);
3538            }
3539        }
3540        throw new SecurityException("No permission tree found for " + permName);
3541    }
3542
3543    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3544        if (s1 == null) {
3545            return s2 == null;
3546        }
3547        if (s2 == null) {
3548            return false;
3549        }
3550        if (s1.getClass() != s2.getClass()) {
3551            return false;
3552        }
3553        return s1.equals(s2);
3554    }
3555
3556    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3557        if (pi1.icon != pi2.icon) return false;
3558        if (pi1.logo != pi2.logo) return false;
3559        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3560        if (!compareStrings(pi1.name, pi2.name)) return false;
3561        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3562        // We'll take care of setting this one.
3563        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3564        // These are not currently stored in settings.
3565        //if (!compareStrings(pi1.group, pi2.group)) return false;
3566        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3567        //if (pi1.labelRes != pi2.labelRes) return false;
3568        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3569        return true;
3570    }
3571
3572    int permissionInfoFootprint(PermissionInfo info) {
3573        int size = info.name.length();
3574        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3575        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3576        return size;
3577    }
3578
3579    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3580        int size = 0;
3581        for (BasePermission perm : mSettings.mPermissions.values()) {
3582            if (perm.uid == tree.uid) {
3583                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3584            }
3585        }
3586        return size;
3587    }
3588
3589    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3590        // We calculate the max size of permissions defined by this uid and throw
3591        // if that plus the size of 'info' would exceed our stated maximum.
3592        if (tree.uid != Process.SYSTEM_UID) {
3593            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3594            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3595                throw new SecurityException("Permission tree size cap exceeded");
3596            }
3597        }
3598    }
3599
3600    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3601        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3602            throw new SecurityException("Label must be specified in permission");
3603        }
3604        BasePermission tree = checkPermissionTreeLP(info.name);
3605        BasePermission bp = mSettings.mPermissions.get(info.name);
3606        boolean added = bp == null;
3607        boolean changed = true;
3608        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3609        if (added) {
3610            enforcePermissionCapLocked(info, tree);
3611            bp = new BasePermission(info.name, tree.sourcePackage,
3612                    BasePermission.TYPE_DYNAMIC);
3613        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3614            throw new SecurityException(
3615                    "Not allowed to modify non-dynamic permission "
3616                    + info.name);
3617        } else {
3618            if (bp.protectionLevel == fixedLevel
3619                    && bp.perm.owner.equals(tree.perm.owner)
3620                    && bp.uid == tree.uid
3621                    && comparePermissionInfos(bp.perm.info, info)) {
3622                changed = false;
3623            }
3624        }
3625        bp.protectionLevel = fixedLevel;
3626        info = new PermissionInfo(info);
3627        info.protectionLevel = fixedLevel;
3628        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3629        bp.perm.info.packageName = tree.perm.info.packageName;
3630        bp.uid = tree.uid;
3631        if (added) {
3632            mSettings.mPermissions.put(info.name, bp);
3633        }
3634        if (changed) {
3635            if (!async) {
3636                mSettings.writeLPr();
3637            } else {
3638                scheduleWriteSettingsLocked();
3639            }
3640        }
3641        return added;
3642    }
3643
3644    @Override
3645    public boolean addPermission(PermissionInfo info) {
3646        synchronized (mPackages) {
3647            return addPermissionLocked(info, false);
3648        }
3649    }
3650
3651    @Override
3652    public boolean addPermissionAsync(PermissionInfo info) {
3653        synchronized (mPackages) {
3654            return addPermissionLocked(info, true);
3655        }
3656    }
3657
3658    @Override
3659    public void removePermission(String name) {
3660        synchronized (mPackages) {
3661            checkPermissionTreeLP(name);
3662            BasePermission bp = mSettings.mPermissions.get(name);
3663            if (bp != null) {
3664                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3665                    throw new SecurityException(
3666                            "Not allowed to modify non-dynamic permission "
3667                            + name);
3668                }
3669                mSettings.mPermissions.remove(name);
3670                mSettings.writeLPr();
3671            }
3672        }
3673    }
3674
3675    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3676            BasePermission bp) {
3677        int index = pkg.requestedPermissions.indexOf(bp.name);
3678        if (index == -1) {
3679            throw new SecurityException("Package " + pkg.packageName
3680                    + " has not requested permission " + bp.name);
3681        }
3682        if (!bp.isRuntime() && !bp.isDevelopment()) {
3683            throw new SecurityException("Permission " + bp.name
3684                    + " is not a changeable permission type");
3685        }
3686    }
3687
3688    @Override
3689    public void grantRuntimePermission(String packageName, String name, final int userId) {
3690        if (!sUserManager.exists(userId)) {
3691            Log.e(TAG, "No such user:" + userId);
3692            return;
3693        }
3694
3695        mContext.enforceCallingOrSelfPermission(
3696                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3697                "grantRuntimePermission");
3698
3699        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3700                "grantRuntimePermission");
3701
3702        final int uid;
3703        final SettingBase sb;
3704
3705        synchronized (mPackages) {
3706            final PackageParser.Package pkg = mPackages.get(packageName);
3707            if (pkg == null) {
3708                throw new IllegalArgumentException("Unknown package: " + packageName);
3709            }
3710
3711            final BasePermission bp = mSettings.mPermissions.get(name);
3712            if (bp == null) {
3713                throw new IllegalArgumentException("Unknown permission: " + name);
3714            }
3715
3716            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3717
3718            // If a permission review is required for legacy apps we represent
3719            // their permissions as always granted runtime ones since we need
3720            // to keep the review required permission flag per user while an
3721            // install permission's state is shared across all users.
3722            if (Build.PERMISSIONS_REVIEW_REQUIRED
3723                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3724                    && bp.isRuntime()) {
3725                return;
3726            }
3727
3728            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3729            sb = (SettingBase) pkg.mExtras;
3730            if (sb == null) {
3731                throw new IllegalArgumentException("Unknown package: " + packageName);
3732            }
3733
3734            final PermissionsState permissionsState = sb.getPermissionsState();
3735
3736            final int flags = permissionsState.getPermissionFlags(name, userId);
3737            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3738                throw new SecurityException("Cannot grant system fixed permission "
3739                        + name + " for package " + packageName);
3740            }
3741
3742            if (bp.isDevelopment()) {
3743                // Development permissions must be handled specially, since they are not
3744                // normal runtime permissions.  For now they apply to all users.
3745                if (permissionsState.grantInstallPermission(bp) !=
3746                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3747                    scheduleWriteSettingsLocked();
3748                }
3749                return;
3750            }
3751
3752            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3753                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3754                return;
3755            }
3756
3757            final int result = permissionsState.grantRuntimePermission(bp, userId);
3758            switch (result) {
3759                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3760                    return;
3761                }
3762
3763                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3764                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3765                    mHandler.post(new Runnable() {
3766                        @Override
3767                        public void run() {
3768                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3769                        }
3770                    });
3771                }
3772                break;
3773            }
3774
3775            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3776
3777            // Not critical if that is lost - app has to request again.
3778            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3779        }
3780
3781        // Only need to do this if user is initialized. Otherwise it's a new user
3782        // and there are no processes running as the user yet and there's no need
3783        // to make an expensive call to remount processes for the changed permissions.
3784        if (READ_EXTERNAL_STORAGE.equals(name)
3785                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3786            final long token = Binder.clearCallingIdentity();
3787            try {
3788                if (sUserManager.isInitialized(userId)) {
3789                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3790                            MountServiceInternal.class);
3791                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3792                }
3793            } finally {
3794                Binder.restoreCallingIdentity(token);
3795            }
3796        }
3797    }
3798
3799    @Override
3800    public void revokeRuntimePermission(String packageName, String name, int userId) {
3801        if (!sUserManager.exists(userId)) {
3802            Log.e(TAG, "No such user:" + userId);
3803            return;
3804        }
3805
3806        mContext.enforceCallingOrSelfPermission(
3807                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3808                "revokeRuntimePermission");
3809
3810        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3811                "revokeRuntimePermission");
3812
3813        final int appId;
3814
3815        synchronized (mPackages) {
3816            final PackageParser.Package pkg = mPackages.get(packageName);
3817            if (pkg == null) {
3818                throw new IllegalArgumentException("Unknown package: " + packageName);
3819            }
3820
3821            final BasePermission bp = mSettings.mPermissions.get(name);
3822            if (bp == null) {
3823                throw new IllegalArgumentException("Unknown permission: " + name);
3824            }
3825
3826            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3827
3828            // If a permission review is required for legacy apps we represent
3829            // their permissions as always granted runtime ones since we need
3830            // to keep the review required permission flag per user while an
3831            // install permission's state is shared across all users.
3832            if (Build.PERMISSIONS_REVIEW_REQUIRED
3833                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3834                    && bp.isRuntime()) {
3835                return;
3836            }
3837
3838            SettingBase sb = (SettingBase) pkg.mExtras;
3839            if (sb == null) {
3840                throw new IllegalArgumentException("Unknown package: " + packageName);
3841            }
3842
3843            final PermissionsState permissionsState = sb.getPermissionsState();
3844
3845            final int flags = permissionsState.getPermissionFlags(name, userId);
3846            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3847                throw new SecurityException("Cannot revoke system fixed permission "
3848                        + name + " for package " + packageName);
3849            }
3850
3851            if (bp.isDevelopment()) {
3852                // Development permissions must be handled specially, since they are not
3853                // normal runtime permissions.  For now they apply to all users.
3854                if (permissionsState.revokeInstallPermission(bp) !=
3855                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3856                    scheduleWriteSettingsLocked();
3857                }
3858                return;
3859            }
3860
3861            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3862                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3863                return;
3864            }
3865
3866            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3867
3868            // Critical, after this call app should never have the permission.
3869            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3870
3871            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3872        }
3873
3874        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3875    }
3876
3877    @Override
3878    public void resetRuntimePermissions() {
3879        mContext.enforceCallingOrSelfPermission(
3880                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3881                "revokeRuntimePermission");
3882
3883        int callingUid = Binder.getCallingUid();
3884        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3885            mContext.enforceCallingOrSelfPermission(
3886                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3887                    "resetRuntimePermissions");
3888        }
3889
3890        synchronized (mPackages) {
3891            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3892            for (int userId : UserManagerService.getInstance().getUserIds()) {
3893                final int packageCount = mPackages.size();
3894                for (int i = 0; i < packageCount; i++) {
3895                    PackageParser.Package pkg = mPackages.valueAt(i);
3896                    if (!(pkg.mExtras instanceof PackageSetting)) {
3897                        continue;
3898                    }
3899                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3900                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3901                }
3902            }
3903        }
3904    }
3905
3906    @Override
3907    public int getPermissionFlags(String name, String packageName, int userId) {
3908        if (!sUserManager.exists(userId)) {
3909            return 0;
3910        }
3911
3912        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3913
3914        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3915                "getPermissionFlags");
3916
3917        synchronized (mPackages) {
3918            final PackageParser.Package pkg = mPackages.get(packageName);
3919            if (pkg == null) {
3920                throw new IllegalArgumentException("Unknown package: " + packageName);
3921            }
3922
3923            final BasePermission bp = mSettings.mPermissions.get(name);
3924            if (bp == null) {
3925                throw new IllegalArgumentException("Unknown permission: " + name);
3926            }
3927
3928            SettingBase sb = (SettingBase) pkg.mExtras;
3929            if (sb == null) {
3930                throw new IllegalArgumentException("Unknown package: " + packageName);
3931            }
3932
3933            PermissionsState permissionsState = sb.getPermissionsState();
3934            return permissionsState.getPermissionFlags(name, userId);
3935        }
3936    }
3937
3938    @Override
3939    public void updatePermissionFlags(String name, String packageName, int flagMask,
3940            int flagValues, int userId) {
3941        if (!sUserManager.exists(userId)) {
3942            return;
3943        }
3944
3945        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3946
3947        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3948                "updatePermissionFlags");
3949
3950        // Only the system can change these flags and nothing else.
3951        if (getCallingUid() != Process.SYSTEM_UID) {
3952            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3953            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3954            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3955            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3956            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3957        }
3958
3959        synchronized (mPackages) {
3960            final PackageParser.Package pkg = mPackages.get(packageName);
3961            if (pkg == null) {
3962                throw new IllegalArgumentException("Unknown package: " + packageName);
3963            }
3964
3965            final BasePermission bp = mSettings.mPermissions.get(name);
3966            if (bp == null) {
3967                throw new IllegalArgumentException("Unknown permission: " + name);
3968            }
3969
3970            SettingBase sb = (SettingBase) pkg.mExtras;
3971            if (sb == null) {
3972                throw new IllegalArgumentException("Unknown package: " + packageName);
3973            }
3974
3975            PermissionsState permissionsState = sb.getPermissionsState();
3976
3977            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3978
3979            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3980                // Install and runtime permissions are stored in different places,
3981                // so figure out what permission changed and persist the change.
3982                if (permissionsState.getInstallPermissionState(name) != null) {
3983                    scheduleWriteSettingsLocked();
3984                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3985                        || hadState) {
3986                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3987                }
3988            }
3989        }
3990    }
3991
3992    /**
3993     * Update the permission flags for all packages and runtime permissions of a user in order
3994     * to allow device or profile owner to remove POLICY_FIXED.
3995     */
3996    @Override
3997    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3998        if (!sUserManager.exists(userId)) {
3999            return;
4000        }
4001
4002        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4003
4004        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4005                "updatePermissionFlagsForAllApps");
4006
4007        // Only the system can change system fixed flags.
4008        if (getCallingUid() != Process.SYSTEM_UID) {
4009            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4010            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4011        }
4012
4013        synchronized (mPackages) {
4014            boolean changed = false;
4015            final int packageCount = mPackages.size();
4016            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4017                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4018                SettingBase sb = (SettingBase) pkg.mExtras;
4019                if (sb == null) {
4020                    continue;
4021                }
4022                PermissionsState permissionsState = sb.getPermissionsState();
4023                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4024                        userId, flagMask, flagValues);
4025            }
4026            if (changed) {
4027                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4028            }
4029        }
4030    }
4031
4032    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4033        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4034                != PackageManager.PERMISSION_GRANTED
4035            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4036                != PackageManager.PERMISSION_GRANTED) {
4037            throw new SecurityException(message + " requires "
4038                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4039                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4040        }
4041    }
4042
4043    @Override
4044    public boolean shouldShowRequestPermissionRationale(String permissionName,
4045            String packageName, int userId) {
4046        if (UserHandle.getCallingUserId() != userId) {
4047            mContext.enforceCallingPermission(
4048                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4049                    "canShowRequestPermissionRationale for user " + userId);
4050        }
4051
4052        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4053        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4054            return false;
4055        }
4056
4057        if (checkPermission(permissionName, packageName, userId)
4058                == PackageManager.PERMISSION_GRANTED) {
4059            return false;
4060        }
4061
4062        final int flags;
4063
4064        final long identity = Binder.clearCallingIdentity();
4065        try {
4066            flags = getPermissionFlags(permissionName,
4067                    packageName, userId);
4068        } finally {
4069            Binder.restoreCallingIdentity(identity);
4070        }
4071
4072        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4073                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4074                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4075
4076        if ((flags & fixedFlags) != 0) {
4077            return false;
4078        }
4079
4080        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4081    }
4082
4083    @Override
4084    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4085        mContext.enforceCallingOrSelfPermission(
4086                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4087                "addOnPermissionsChangeListener");
4088
4089        synchronized (mPackages) {
4090            mOnPermissionChangeListeners.addListenerLocked(listener);
4091        }
4092    }
4093
4094    @Override
4095    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4096        synchronized (mPackages) {
4097            mOnPermissionChangeListeners.removeListenerLocked(listener);
4098        }
4099    }
4100
4101    @Override
4102    public boolean isProtectedBroadcast(String actionName) {
4103        synchronized (mPackages) {
4104            if (mProtectedBroadcasts.contains(actionName)) {
4105                return true;
4106            } else if (actionName != null) {
4107                // TODO: remove these terrible hacks
4108                if (actionName.startsWith("android.net.netmon.lingerExpired")
4109                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4110                    return true;
4111                }
4112            }
4113        }
4114        return false;
4115    }
4116
4117    @Override
4118    public int checkSignatures(String pkg1, String pkg2) {
4119        synchronized (mPackages) {
4120            final PackageParser.Package p1 = mPackages.get(pkg1);
4121            final PackageParser.Package p2 = mPackages.get(pkg2);
4122            if (p1 == null || p1.mExtras == null
4123                    || p2 == null || p2.mExtras == null) {
4124                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4125            }
4126            return compareSignatures(p1.mSignatures, p2.mSignatures);
4127        }
4128    }
4129
4130    @Override
4131    public int checkUidSignatures(int uid1, int uid2) {
4132        // Map to base uids.
4133        uid1 = UserHandle.getAppId(uid1);
4134        uid2 = UserHandle.getAppId(uid2);
4135        // reader
4136        synchronized (mPackages) {
4137            Signature[] s1;
4138            Signature[] s2;
4139            Object obj = mSettings.getUserIdLPr(uid1);
4140            if (obj != null) {
4141                if (obj instanceof SharedUserSetting) {
4142                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4143                } else if (obj instanceof PackageSetting) {
4144                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4145                } else {
4146                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4147                }
4148            } else {
4149                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4150            }
4151            obj = mSettings.getUserIdLPr(uid2);
4152            if (obj != null) {
4153                if (obj instanceof SharedUserSetting) {
4154                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4155                } else if (obj instanceof PackageSetting) {
4156                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4157                } else {
4158                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4159                }
4160            } else {
4161                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4162            }
4163            return compareSignatures(s1, s2);
4164        }
4165    }
4166
4167    private void killUid(int appId, int userId, String reason) {
4168        final long identity = Binder.clearCallingIdentity();
4169        try {
4170            IActivityManager am = ActivityManagerNative.getDefault();
4171            if (am != null) {
4172                try {
4173                    am.killUid(appId, userId, reason);
4174                } catch (RemoteException e) {
4175                    /* ignore - same process */
4176                }
4177            }
4178        } finally {
4179            Binder.restoreCallingIdentity(identity);
4180        }
4181    }
4182
4183    /**
4184     * Compares two sets of signatures. Returns:
4185     * <br />
4186     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4187     * <br />
4188     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4189     * <br />
4190     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4191     * <br />
4192     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4193     * <br />
4194     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4195     */
4196    static int compareSignatures(Signature[] s1, Signature[] s2) {
4197        if (s1 == null) {
4198            return s2 == null
4199                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4200                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4201        }
4202
4203        if (s2 == null) {
4204            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4205        }
4206
4207        if (s1.length != s2.length) {
4208            return PackageManager.SIGNATURE_NO_MATCH;
4209        }
4210
4211        // Since both signature sets are of size 1, we can compare without HashSets.
4212        if (s1.length == 1) {
4213            return s1[0].equals(s2[0]) ?
4214                    PackageManager.SIGNATURE_MATCH :
4215                    PackageManager.SIGNATURE_NO_MATCH;
4216        }
4217
4218        ArraySet<Signature> set1 = new ArraySet<Signature>();
4219        for (Signature sig : s1) {
4220            set1.add(sig);
4221        }
4222        ArraySet<Signature> set2 = new ArraySet<Signature>();
4223        for (Signature sig : s2) {
4224            set2.add(sig);
4225        }
4226        // Make sure s2 contains all signatures in s1.
4227        if (set1.equals(set2)) {
4228            return PackageManager.SIGNATURE_MATCH;
4229        }
4230        return PackageManager.SIGNATURE_NO_MATCH;
4231    }
4232
4233    /**
4234     * If the database version for this type of package (internal storage or
4235     * external storage) is less than the version where package signatures
4236     * were updated, return true.
4237     */
4238    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4239        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4240        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4241    }
4242
4243    /**
4244     * Used for backward compatibility to make sure any packages with
4245     * certificate chains get upgraded to the new style. {@code existingSigs}
4246     * will be in the old format (since they were stored on disk from before the
4247     * system upgrade) and {@code scannedSigs} will be in the newer format.
4248     */
4249    private int compareSignaturesCompat(PackageSignatures existingSigs,
4250            PackageParser.Package scannedPkg) {
4251        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4252            return PackageManager.SIGNATURE_NO_MATCH;
4253        }
4254
4255        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4256        for (Signature sig : existingSigs.mSignatures) {
4257            existingSet.add(sig);
4258        }
4259        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4260        for (Signature sig : scannedPkg.mSignatures) {
4261            try {
4262                Signature[] chainSignatures = sig.getChainSignatures();
4263                for (Signature chainSig : chainSignatures) {
4264                    scannedCompatSet.add(chainSig);
4265                }
4266            } catch (CertificateEncodingException e) {
4267                scannedCompatSet.add(sig);
4268            }
4269        }
4270        /*
4271         * Make sure the expanded scanned set contains all signatures in the
4272         * existing one.
4273         */
4274        if (scannedCompatSet.equals(existingSet)) {
4275            // Migrate the old signatures to the new scheme.
4276            existingSigs.assignSignatures(scannedPkg.mSignatures);
4277            // The new KeySets will be re-added later in the scanning process.
4278            synchronized (mPackages) {
4279                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4280            }
4281            return PackageManager.SIGNATURE_MATCH;
4282        }
4283        return PackageManager.SIGNATURE_NO_MATCH;
4284    }
4285
4286    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4287        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4288        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4289    }
4290
4291    private int compareSignaturesRecover(PackageSignatures existingSigs,
4292            PackageParser.Package scannedPkg) {
4293        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4294            return PackageManager.SIGNATURE_NO_MATCH;
4295        }
4296
4297        String msg = null;
4298        try {
4299            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4300                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4301                        + scannedPkg.packageName);
4302                return PackageManager.SIGNATURE_MATCH;
4303            }
4304        } catch (CertificateException e) {
4305            msg = e.getMessage();
4306        }
4307
4308        logCriticalInfo(Log.INFO,
4309                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4310        return PackageManager.SIGNATURE_NO_MATCH;
4311    }
4312
4313    @Override
4314    public String[] getPackagesForUid(int uid) {
4315        uid = UserHandle.getAppId(uid);
4316        // reader
4317        synchronized (mPackages) {
4318            Object obj = mSettings.getUserIdLPr(uid);
4319            if (obj instanceof SharedUserSetting) {
4320                final SharedUserSetting sus = (SharedUserSetting) obj;
4321                final int N = sus.packages.size();
4322                final String[] res = new String[N];
4323                final Iterator<PackageSetting> it = sus.packages.iterator();
4324                int i = 0;
4325                while (it.hasNext()) {
4326                    res[i++] = it.next().name;
4327                }
4328                return res;
4329            } else if (obj instanceof PackageSetting) {
4330                final PackageSetting ps = (PackageSetting) obj;
4331                return new String[] { ps.name };
4332            }
4333        }
4334        return null;
4335    }
4336
4337    @Override
4338    public String getNameForUid(int uid) {
4339        // reader
4340        synchronized (mPackages) {
4341            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4342            if (obj instanceof SharedUserSetting) {
4343                final SharedUserSetting sus = (SharedUserSetting) obj;
4344                return sus.name + ":" + sus.userId;
4345            } else if (obj instanceof PackageSetting) {
4346                final PackageSetting ps = (PackageSetting) obj;
4347                return ps.name;
4348            }
4349        }
4350        return null;
4351    }
4352
4353    @Override
4354    public int getUidForSharedUser(String sharedUserName) {
4355        if(sharedUserName == null) {
4356            return -1;
4357        }
4358        // reader
4359        synchronized (mPackages) {
4360            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4361            if (suid == null) {
4362                return -1;
4363            }
4364            return suid.userId;
4365        }
4366    }
4367
4368    @Override
4369    public int getFlagsForUid(int uid) {
4370        synchronized (mPackages) {
4371            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4372            if (obj instanceof SharedUserSetting) {
4373                final SharedUserSetting sus = (SharedUserSetting) obj;
4374                return sus.pkgFlags;
4375            } else if (obj instanceof PackageSetting) {
4376                final PackageSetting ps = (PackageSetting) obj;
4377                return ps.pkgFlags;
4378            }
4379        }
4380        return 0;
4381    }
4382
4383    @Override
4384    public int getPrivateFlagsForUid(int uid) {
4385        synchronized (mPackages) {
4386            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4387            if (obj instanceof SharedUserSetting) {
4388                final SharedUserSetting sus = (SharedUserSetting) obj;
4389                return sus.pkgPrivateFlags;
4390            } else if (obj instanceof PackageSetting) {
4391                final PackageSetting ps = (PackageSetting) obj;
4392                return ps.pkgPrivateFlags;
4393            }
4394        }
4395        return 0;
4396    }
4397
4398    @Override
4399    public boolean isUidPrivileged(int uid) {
4400        uid = UserHandle.getAppId(uid);
4401        // reader
4402        synchronized (mPackages) {
4403            Object obj = mSettings.getUserIdLPr(uid);
4404            if (obj instanceof SharedUserSetting) {
4405                final SharedUserSetting sus = (SharedUserSetting) obj;
4406                final Iterator<PackageSetting> it = sus.packages.iterator();
4407                while (it.hasNext()) {
4408                    if (it.next().isPrivileged()) {
4409                        return true;
4410                    }
4411                }
4412            } else if (obj instanceof PackageSetting) {
4413                final PackageSetting ps = (PackageSetting) obj;
4414                return ps.isPrivileged();
4415            }
4416        }
4417        return false;
4418    }
4419
4420    @Override
4421    public String[] getAppOpPermissionPackages(String permissionName) {
4422        synchronized (mPackages) {
4423            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4424            if (pkgs == null) {
4425                return null;
4426            }
4427            return pkgs.toArray(new String[pkgs.size()]);
4428        }
4429    }
4430
4431    @Override
4432    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4433            int flags, int userId) {
4434        if (!sUserManager.exists(userId)) return null;
4435        flags = updateFlagsForResolve(flags, userId, intent);
4436        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4437        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4438        final ResolveInfo bestChoice =
4439                chooseBestActivity(intent, resolvedType, flags, query, userId);
4440
4441        if (isEphemeralAllowed(intent, query, userId)) {
4442            final EphemeralResolveInfo ai =
4443                    getEphemeralResolveInfo(intent, resolvedType, userId);
4444            if (ai != null) {
4445                if (DEBUG_EPHEMERAL) {
4446                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4447                }
4448                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4449                bestChoice.ephemeralResolveInfo = ai;
4450            }
4451        }
4452        return bestChoice;
4453    }
4454
4455    @Override
4456    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4457            IntentFilter filter, int match, ComponentName activity) {
4458        final int userId = UserHandle.getCallingUserId();
4459        if (DEBUG_PREFERRED) {
4460            Log.v(TAG, "setLastChosenActivity intent=" + intent
4461                + " resolvedType=" + resolvedType
4462                + " flags=" + flags
4463                + " filter=" + filter
4464                + " match=" + match
4465                + " activity=" + activity);
4466            filter.dump(new PrintStreamPrinter(System.out), "    ");
4467        }
4468        intent.setComponent(null);
4469        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4470        // Find any earlier preferred or last chosen entries and nuke them
4471        findPreferredActivity(intent, resolvedType,
4472                flags, query, 0, false, true, false, userId);
4473        // Add the new activity as the last chosen for this filter
4474        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4475                "Setting last chosen");
4476    }
4477
4478    @Override
4479    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4480        final int userId = UserHandle.getCallingUserId();
4481        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4482        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4483        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4484                false, false, false, userId);
4485    }
4486
4487
4488    private boolean isEphemeralAllowed(
4489            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4490        // Short circuit and return early if possible.
4491        if (DISABLE_EPHEMERAL_APPS) {
4492            return false;
4493        }
4494        final int callingUser = UserHandle.getCallingUserId();
4495        if (callingUser != UserHandle.USER_SYSTEM) {
4496            return false;
4497        }
4498        if (mEphemeralResolverConnection == null) {
4499            return false;
4500        }
4501        if (intent.getComponent() != null) {
4502            return false;
4503        }
4504        if (intent.getPackage() != null) {
4505            return false;
4506        }
4507        final boolean isWebUri = hasWebURI(intent);
4508        if (!isWebUri) {
4509            return false;
4510        }
4511        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4512        synchronized (mPackages) {
4513            final int count = resolvedActivites.size();
4514            for (int n = 0; n < count; n++) {
4515                ResolveInfo info = resolvedActivites.get(n);
4516                String packageName = info.activityInfo.packageName;
4517                PackageSetting ps = mSettings.mPackages.get(packageName);
4518                if (ps != null) {
4519                    // Try to get the status from User settings first
4520                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4521                    int status = (int) (packedStatus >> 32);
4522                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4523                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4524                        if (DEBUG_EPHEMERAL) {
4525                            Slog.v(TAG, "DENY ephemeral apps;"
4526                                + " pkg: " + packageName + ", status: " + status);
4527                        }
4528                        return false;
4529                    }
4530                }
4531            }
4532        }
4533        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4534        return true;
4535    }
4536
4537    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4538            int userId) {
4539        MessageDigest digest = null;
4540        try {
4541            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4542        } catch (NoSuchAlgorithmException e) {
4543            // If we can't create a digest, ignore ephemeral apps.
4544            return null;
4545        }
4546
4547        final byte[] hostBytes = intent.getData().getHost().getBytes();
4548        final byte[] digestBytes = digest.digest(hostBytes);
4549        int shaPrefix =
4550                digestBytes[0] << 24
4551                | digestBytes[1] << 16
4552                | digestBytes[2] << 8
4553                | digestBytes[3] << 0;
4554        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4555                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4556        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4557            // No hash prefix match; there are no ephemeral apps for this domain.
4558            return null;
4559        }
4560        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4561            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4562            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4563                continue;
4564            }
4565            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4566            // No filters; this should never happen.
4567            if (filters.isEmpty()) {
4568                continue;
4569            }
4570            // We have a domain match; resolve the filters to see if anything matches.
4571            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4572            for (int j = filters.size() - 1; j >= 0; --j) {
4573                final EphemeralResolveIntentInfo intentInfo =
4574                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4575                ephemeralResolver.addFilter(intentInfo);
4576            }
4577            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4578                    intent, resolvedType, false /*defaultOnly*/, userId);
4579            if (!matchedResolveInfoList.isEmpty()) {
4580                return matchedResolveInfoList.get(0);
4581            }
4582        }
4583        // Hash or filter mis-match; no ephemeral apps for this domain.
4584        return null;
4585    }
4586
4587    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4588            int flags, List<ResolveInfo> query, int userId) {
4589        if (query != null) {
4590            final int N = query.size();
4591            if (N == 1) {
4592                return query.get(0);
4593            } else if (N > 1) {
4594                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4595                // If there is more than one activity with the same priority,
4596                // then let the user decide between them.
4597                ResolveInfo r0 = query.get(0);
4598                ResolveInfo r1 = query.get(1);
4599                if (DEBUG_INTENT_MATCHING || debug) {
4600                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4601                            + r1.activityInfo.name + "=" + r1.priority);
4602                }
4603                // If the first activity has a higher priority, or a different
4604                // default, then it is always desirable to pick it.
4605                if (r0.priority != r1.priority
4606                        || r0.preferredOrder != r1.preferredOrder
4607                        || r0.isDefault != r1.isDefault) {
4608                    return query.get(0);
4609                }
4610                // If we have saved a preference for a preferred activity for
4611                // this Intent, use that.
4612                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4613                        flags, query, r0.priority, true, false, debug, userId);
4614                if (ri != null) {
4615                    return ri;
4616                }
4617                ri = new ResolveInfo(mResolveInfo);
4618                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4619                ri.activityInfo.applicationInfo = new ApplicationInfo(
4620                        ri.activityInfo.applicationInfo);
4621                if (userId != 0) {
4622                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4623                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4624                }
4625                // Make sure that the resolver is displayable in car mode
4626                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4627                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4628                return ri;
4629            }
4630        }
4631        return null;
4632    }
4633
4634    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4635            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4636        final int N = query.size();
4637        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4638                .get(userId);
4639        // Get the list of persistent preferred activities that handle the intent
4640        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4641        List<PersistentPreferredActivity> pprefs = ppir != null
4642                ? ppir.queryIntent(intent, resolvedType,
4643                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4644                : null;
4645        if (pprefs != null && pprefs.size() > 0) {
4646            final int M = pprefs.size();
4647            for (int i=0; i<M; i++) {
4648                final PersistentPreferredActivity ppa = pprefs.get(i);
4649                if (DEBUG_PREFERRED || debug) {
4650                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4651                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4652                            + "\n  component=" + ppa.mComponent);
4653                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4654                }
4655                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4656                        flags | MATCH_DISABLED_COMPONENTS, userId);
4657                if (DEBUG_PREFERRED || debug) {
4658                    Slog.v(TAG, "Found persistent preferred activity:");
4659                    if (ai != null) {
4660                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4661                    } else {
4662                        Slog.v(TAG, "  null");
4663                    }
4664                }
4665                if (ai == null) {
4666                    // This previously registered persistent preferred activity
4667                    // component is no longer known. Ignore it and do NOT remove it.
4668                    continue;
4669                }
4670                for (int j=0; j<N; j++) {
4671                    final ResolveInfo ri = query.get(j);
4672                    if (!ri.activityInfo.applicationInfo.packageName
4673                            .equals(ai.applicationInfo.packageName)) {
4674                        continue;
4675                    }
4676                    if (!ri.activityInfo.name.equals(ai.name)) {
4677                        continue;
4678                    }
4679                    //  Found a persistent preference that can handle the intent.
4680                    if (DEBUG_PREFERRED || debug) {
4681                        Slog.v(TAG, "Returning persistent preferred activity: " +
4682                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4683                    }
4684                    return ri;
4685                }
4686            }
4687        }
4688        return null;
4689    }
4690
4691    // TODO: handle preferred activities missing while user has amnesia
4692    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4693            List<ResolveInfo> query, int priority, boolean always,
4694            boolean removeMatches, boolean debug, int userId) {
4695        if (!sUserManager.exists(userId)) return null;
4696        flags = updateFlagsForResolve(flags, userId, intent);
4697        // writer
4698        synchronized (mPackages) {
4699            if (intent.getSelector() != null) {
4700                intent = intent.getSelector();
4701            }
4702            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4703
4704            // Try to find a matching persistent preferred activity.
4705            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4706                    debug, userId);
4707
4708            // If a persistent preferred activity matched, use it.
4709            if (pri != null) {
4710                return pri;
4711            }
4712
4713            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4714            // Get the list of preferred activities that handle the intent
4715            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4716            List<PreferredActivity> prefs = pir != null
4717                    ? pir.queryIntent(intent, resolvedType,
4718                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4719                    : null;
4720            if (prefs != null && prefs.size() > 0) {
4721                boolean changed = false;
4722                try {
4723                    // First figure out how good the original match set is.
4724                    // We will only allow preferred activities that came
4725                    // from the same match quality.
4726                    int match = 0;
4727
4728                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4729
4730                    final int N = query.size();
4731                    for (int j=0; j<N; j++) {
4732                        final ResolveInfo ri = query.get(j);
4733                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4734                                + ": 0x" + Integer.toHexString(match));
4735                        if (ri.match > match) {
4736                            match = ri.match;
4737                        }
4738                    }
4739
4740                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4741                            + Integer.toHexString(match));
4742
4743                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4744                    final int M = prefs.size();
4745                    for (int i=0; i<M; i++) {
4746                        final PreferredActivity pa = prefs.get(i);
4747                        if (DEBUG_PREFERRED || debug) {
4748                            Slog.v(TAG, "Checking PreferredActivity ds="
4749                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4750                                    + "\n  component=" + pa.mPref.mComponent);
4751                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4752                        }
4753                        if (pa.mPref.mMatch != match) {
4754                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4755                                    + Integer.toHexString(pa.mPref.mMatch));
4756                            continue;
4757                        }
4758                        // If it's not an "always" type preferred activity and that's what we're
4759                        // looking for, skip it.
4760                        if (always && !pa.mPref.mAlways) {
4761                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4762                            continue;
4763                        }
4764                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4765                                flags | MATCH_DISABLED_COMPONENTS, userId);
4766                        if (DEBUG_PREFERRED || debug) {
4767                            Slog.v(TAG, "Found preferred activity:");
4768                            if (ai != null) {
4769                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4770                            } else {
4771                                Slog.v(TAG, "  null");
4772                            }
4773                        }
4774                        if (ai == null) {
4775                            // This previously registered preferred activity
4776                            // component is no longer known.  Most likely an update
4777                            // to the app was installed and in the new version this
4778                            // component no longer exists.  Clean it up by removing
4779                            // it from the preferred activities list, and skip it.
4780                            Slog.w(TAG, "Removing dangling preferred activity: "
4781                                    + pa.mPref.mComponent);
4782                            pir.removeFilter(pa);
4783                            changed = true;
4784                            continue;
4785                        }
4786                        for (int j=0; j<N; j++) {
4787                            final ResolveInfo ri = query.get(j);
4788                            if (!ri.activityInfo.applicationInfo.packageName
4789                                    .equals(ai.applicationInfo.packageName)) {
4790                                continue;
4791                            }
4792                            if (!ri.activityInfo.name.equals(ai.name)) {
4793                                continue;
4794                            }
4795
4796                            if (removeMatches) {
4797                                pir.removeFilter(pa);
4798                                changed = true;
4799                                if (DEBUG_PREFERRED) {
4800                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4801                                }
4802                                break;
4803                            }
4804
4805                            // Okay we found a previously set preferred or last chosen app.
4806                            // If the result set is different from when this
4807                            // was created, we need to clear it and re-ask the
4808                            // user their preference, if we're looking for an "always" type entry.
4809                            if (always && !pa.mPref.sameSet(query)) {
4810                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4811                                        + intent + " type " + resolvedType);
4812                                if (DEBUG_PREFERRED) {
4813                                    Slog.v(TAG, "Removing preferred activity since set changed "
4814                                            + pa.mPref.mComponent);
4815                                }
4816                                pir.removeFilter(pa);
4817                                // Re-add the filter as a "last chosen" entry (!always)
4818                                PreferredActivity lastChosen = new PreferredActivity(
4819                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4820                                pir.addFilter(lastChosen);
4821                                changed = true;
4822                                return null;
4823                            }
4824
4825                            // Yay! Either the set matched or we're looking for the last chosen
4826                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4827                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4828                            return ri;
4829                        }
4830                    }
4831                } finally {
4832                    if (changed) {
4833                        if (DEBUG_PREFERRED) {
4834                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4835                        }
4836                        scheduleWritePackageRestrictionsLocked(userId);
4837                    }
4838                }
4839            }
4840        }
4841        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4842        return null;
4843    }
4844
4845    /*
4846     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4847     */
4848    @Override
4849    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4850            int targetUserId) {
4851        mContext.enforceCallingOrSelfPermission(
4852                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4853        List<CrossProfileIntentFilter> matches =
4854                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4855        if (matches != null) {
4856            int size = matches.size();
4857            for (int i = 0; i < size; i++) {
4858                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4859            }
4860        }
4861        if (hasWebURI(intent)) {
4862            // cross-profile app linking works only towards the parent.
4863            final UserInfo parent = getProfileParent(sourceUserId);
4864            synchronized(mPackages) {
4865                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4866                        intent, resolvedType, 0, sourceUserId, parent.id);
4867                return xpDomainInfo != null;
4868            }
4869        }
4870        return false;
4871    }
4872
4873    private UserInfo getProfileParent(int userId) {
4874        final long identity = Binder.clearCallingIdentity();
4875        try {
4876            return sUserManager.getProfileParent(userId);
4877        } finally {
4878            Binder.restoreCallingIdentity(identity);
4879        }
4880    }
4881
4882    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4883            String resolvedType, int userId) {
4884        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4885        if (resolver != null) {
4886            return resolver.queryIntent(intent, resolvedType, false, userId);
4887        }
4888        return null;
4889    }
4890
4891    @Override
4892    public List<ResolveInfo> queryIntentActivities(Intent intent,
4893            String resolvedType, int flags, int userId) {
4894        if (!sUserManager.exists(userId)) return Collections.emptyList();
4895        flags = updateFlagsForResolve(flags, userId, intent);
4896        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4897        ComponentName comp = intent.getComponent();
4898        if (comp == null) {
4899            if (intent.getSelector() != null) {
4900                intent = intent.getSelector();
4901                comp = intent.getComponent();
4902            }
4903        }
4904
4905        if (comp != null) {
4906            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4907            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4908            if (ai != null) {
4909                final ResolveInfo ri = new ResolveInfo();
4910                ri.activityInfo = ai;
4911                list.add(ri);
4912            }
4913            return list;
4914        }
4915
4916        // reader
4917        synchronized (mPackages) {
4918            final String pkgName = intent.getPackage();
4919            if (pkgName == null) {
4920                List<CrossProfileIntentFilter> matchingFilters =
4921                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4922                // Check for results that need to skip the current profile.
4923                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4924                        resolvedType, flags, userId);
4925                if (xpResolveInfo != null) {
4926                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4927                    result.add(xpResolveInfo);
4928                    return filterIfNotSystemUser(result, userId);
4929                }
4930
4931                // Check for results in the current profile.
4932                List<ResolveInfo> result = mActivities.queryIntent(
4933                        intent, resolvedType, flags, userId);
4934                result = filterIfNotSystemUser(result, userId);
4935
4936                // Check for cross profile results.
4937                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4938                xpResolveInfo = queryCrossProfileIntents(
4939                        matchingFilters, intent, resolvedType, flags, userId,
4940                        hasNonNegativePriorityResult);
4941                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4942                    boolean isVisibleToUser = filterIfNotSystemUser(
4943                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4944                    if (isVisibleToUser) {
4945                        result.add(xpResolveInfo);
4946                        Collections.sort(result, mResolvePrioritySorter);
4947                    }
4948                }
4949                if (hasWebURI(intent)) {
4950                    CrossProfileDomainInfo xpDomainInfo = null;
4951                    final UserInfo parent = getProfileParent(userId);
4952                    if (parent != null) {
4953                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4954                                flags, userId, parent.id);
4955                    }
4956                    if (xpDomainInfo != null) {
4957                        if (xpResolveInfo != null) {
4958                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4959                            // in the result.
4960                            result.remove(xpResolveInfo);
4961                        }
4962                        if (result.size() == 0) {
4963                            result.add(xpDomainInfo.resolveInfo);
4964                            return result;
4965                        }
4966                    } else if (result.size() <= 1) {
4967                        return result;
4968                    }
4969                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4970                            xpDomainInfo, userId);
4971                    Collections.sort(result, mResolvePrioritySorter);
4972                }
4973                return result;
4974            }
4975            final PackageParser.Package pkg = mPackages.get(pkgName);
4976            if (pkg != null) {
4977                return filterIfNotSystemUser(
4978                        mActivities.queryIntentForPackage(
4979                                intent, resolvedType, flags, pkg.activities, userId),
4980                        userId);
4981            }
4982            return new ArrayList<ResolveInfo>();
4983        }
4984    }
4985
4986    private static class CrossProfileDomainInfo {
4987        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4988        ResolveInfo resolveInfo;
4989        /* Best domain verification status of the activities found in the other profile */
4990        int bestDomainVerificationStatus;
4991    }
4992
4993    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4994            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4995        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4996                sourceUserId)) {
4997            return null;
4998        }
4999        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5000                resolvedType, flags, parentUserId);
5001
5002        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5003            return null;
5004        }
5005        CrossProfileDomainInfo result = null;
5006        int size = resultTargetUser.size();
5007        for (int i = 0; i < size; i++) {
5008            ResolveInfo riTargetUser = resultTargetUser.get(i);
5009            // Intent filter verification is only for filters that specify a host. So don't return
5010            // those that handle all web uris.
5011            if (riTargetUser.handleAllWebDataURI) {
5012                continue;
5013            }
5014            String packageName = riTargetUser.activityInfo.packageName;
5015            PackageSetting ps = mSettings.mPackages.get(packageName);
5016            if (ps == null) {
5017                continue;
5018            }
5019            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5020            int status = (int)(verificationState >> 32);
5021            if (result == null) {
5022                result = new CrossProfileDomainInfo();
5023                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5024                        sourceUserId, parentUserId);
5025                result.bestDomainVerificationStatus = status;
5026            } else {
5027                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5028                        result.bestDomainVerificationStatus);
5029            }
5030        }
5031        // Don't consider matches with status NEVER across profiles.
5032        if (result != null && result.bestDomainVerificationStatus
5033                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5034            return null;
5035        }
5036        return result;
5037    }
5038
5039    /**
5040     * Verification statuses are ordered from the worse to the best, except for
5041     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5042     */
5043    private int bestDomainVerificationStatus(int status1, int status2) {
5044        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5045            return status2;
5046        }
5047        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5048            return status1;
5049        }
5050        return (int) MathUtils.max(status1, status2);
5051    }
5052
5053    private boolean isUserEnabled(int userId) {
5054        long callingId = Binder.clearCallingIdentity();
5055        try {
5056            UserInfo userInfo = sUserManager.getUserInfo(userId);
5057            return userInfo != null && userInfo.isEnabled();
5058        } finally {
5059            Binder.restoreCallingIdentity(callingId);
5060        }
5061    }
5062
5063    /**
5064     * Filter out activities with systemUserOnly flag set, when current user is not System.
5065     *
5066     * @return filtered list
5067     */
5068    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5069        if (userId == UserHandle.USER_SYSTEM) {
5070            return resolveInfos;
5071        }
5072        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5073            ResolveInfo info = resolveInfos.get(i);
5074            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5075                resolveInfos.remove(i);
5076            }
5077        }
5078        return resolveInfos;
5079    }
5080
5081    /**
5082     * @param resolveInfos list of resolve infos in descending priority order
5083     * @return if the list contains a resolve info with non-negative priority
5084     */
5085    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5086        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5087    }
5088
5089    private static boolean hasWebURI(Intent intent) {
5090        if (intent.getData() == null) {
5091            return false;
5092        }
5093        final String scheme = intent.getScheme();
5094        if (TextUtils.isEmpty(scheme)) {
5095            return false;
5096        }
5097        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5098    }
5099
5100    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5101            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5102            int userId) {
5103        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5104
5105        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5106            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5107                    candidates.size());
5108        }
5109
5110        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5111        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5112        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5113        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5114        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5115        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5116
5117        synchronized (mPackages) {
5118            final int count = candidates.size();
5119            // First, try to use linked apps. Partition the candidates into four lists:
5120            // one for the final results, one for the "do not use ever", one for "undefined status"
5121            // and finally one for "browser app type".
5122            for (int n=0; n<count; n++) {
5123                ResolveInfo info = candidates.get(n);
5124                String packageName = info.activityInfo.packageName;
5125                PackageSetting ps = mSettings.mPackages.get(packageName);
5126                if (ps != null) {
5127                    // Add to the special match all list (Browser use case)
5128                    if (info.handleAllWebDataURI) {
5129                        matchAllList.add(info);
5130                        continue;
5131                    }
5132                    // Try to get the status from User settings first
5133                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5134                    int status = (int)(packedStatus >> 32);
5135                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5136                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5137                        if (DEBUG_DOMAIN_VERIFICATION) {
5138                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5139                                    + " : linkgen=" + linkGeneration);
5140                        }
5141                        // Use link-enabled generation as preferredOrder, i.e.
5142                        // prefer newly-enabled over earlier-enabled.
5143                        info.preferredOrder = linkGeneration;
5144                        alwaysList.add(info);
5145                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5146                        if (DEBUG_DOMAIN_VERIFICATION) {
5147                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5148                        }
5149                        neverList.add(info);
5150                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5151                        if (DEBUG_DOMAIN_VERIFICATION) {
5152                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5153                        }
5154                        alwaysAskList.add(info);
5155                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5156                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5157                        if (DEBUG_DOMAIN_VERIFICATION) {
5158                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5159                        }
5160                        undefinedList.add(info);
5161                    }
5162                }
5163            }
5164
5165            // We'll want to include browser possibilities in a few cases
5166            boolean includeBrowser = false;
5167
5168            // First try to add the "always" resolution(s) for the current user, if any
5169            if (alwaysList.size() > 0) {
5170                result.addAll(alwaysList);
5171            } else {
5172                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5173                result.addAll(undefinedList);
5174                // Maybe add one for the other profile.
5175                if (xpDomainInfo != null && (
5176                        xpDomainInfo.bestDomainVerificationStatus
5177                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5178                    result.add(xpDomainInfo.resolveInfo);
5179                }
5180                includeBrowser = true;
5181            }
5182
5183            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5184            // If there were 'always' entries their preferred order has been set, so we also
5185            // back that off to make the alternatives equivalent
5186            if (alwaysAskList.size() > 0) {
5187                for (ResolveInfo i : result) {
5188                    i.preferredOrder = 0;
5189                }
5190                result.addAll(alwaysAskList);
5191                includeBrowser = true;
5192            }
5193
5194            if (includeBrowser) {
5195                // Also add browsers (all of them or only the default one)
5196                if (DEBUG_DOMAIN_VERIFICATION) {
5197                    Slog.v(TAG, "   ...including browsers in candidate set");
5198                }
5199                if ((matchFlags & MATCH_ALL) != 0) {
5200                    result.addAll(matchAllList);
5201                } else {
5202                    // Browser/generic handling case.  If there's a default browser, go straight
5203                    // to that (but only if there is no other higher-priority match).
5204                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5205                    int maxMatchPrio = 0;
5206                    ResolveInfo defaultBrowserMatch = null;
5207                    final int numCandidates = matchAllList.size();
5208                    for (int n = 0; n < numCandidates; n++) {
5209                        ResolveInfo info = matchAllList.get(n);
5210                        // track the highest overall match priority...
5211                        if (info.priority > maxMatchPrio) {
5212                            maxMatchPrio = info.priority;
5213                        }
5214                        // ...and the highest-priority default browser match
5215                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5216                            if (defaultBrowserMatch == null
5217                                    || (defaultBrowserMatch.priority < info.priority)) {
5218                                if (debug) {
5219                                    Slog.v(TAG, "Considering default browser match " + info);
5220                                }
5221                                defaultBrowserMatch = info;
5222                            }
5223                        }
5224                    }
5225                    if (defaultBrowserMatch != null
5226                            && defaultBrowserMatch.priority >= maxMatchPrio
5227                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5228                    {
5229                        if (debug) {
5230                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5231                        }
5232                        result.add(defaultBrowserMatch);
5233                    } else {
5234                        result.addAll(matchAllList);
5235                    }
5236                }
5237
5238                // If there is nothing selected, add all candidates and remove the ones that the user
5239                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5240                if (result.size() == 0) {
5241                    result.addAll(candidates);
5242                    result.removeAll(neverList);
5243                }
5244            }
5245        }
5246        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5247            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5248                    result.size());
5249            for (ResolveInfo info : result) {
5250                Slog.v(TAG, "  + " + info.activityInfo);
5251            }
5252        }
5253        return result;
5254    }
5255
5256    // Returns a packed value as a long:
5257    //
5258    // high 'int'-sized word: link status: undefined/ask/never/always.
5259    // low 'int'-sized word: relative priority among 'always' results.
5260    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5261        long result = ps.getDomainVerificationStatusForUser(userId);
5262        // if none available, get the master status
5263        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5264            if (ps.getIntentFilterVerificationInfo() != null) {
5265                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5266            }
5267        }
5268        return result;
5269    }
5270
5271    private ResolveInfo querySkipCurrentProfileIntents(
5272            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5273            int flags, int sourceUserId) {
5274        if (matchingFilters != null) {
5275            int size = matchingFilters.size();
5276            for (int i = 0; i < size; i ++) {
5277                CrossProfileIntentFilter filter = matchingFilters.get(i);
5278                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5279                    // Checking if there are activities in the target user that can handle the
5280                    // intent.
5281                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5282                            resolvedType, flags, sourceUserId);
5283                    if (resolveInfo != null) {
5284                        return resolveInfo;
5285                    }
5286                }
5287            }
5288        }
5289        return null;
5290    }
5291
5292    // Return matching ResolveInfo in target user if any.
5293    private ResolveInfo queryCrossProfileIntents(
5294            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5295            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5296        if (matchingFilters != null) {
5297            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5298            // match the same intent. For performance reasons, it is better not to
5299            // run queryIntent twice for the same userId
5300            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5301            int size = matchingFilters.size();
5302            for (int i = 0; i < size; i++) {
5303                CrossProfileIntentFilter filter = matchingFilters.get(i);
5304                int targetUserId = filter.getTargetUserId();
5305                boolean skipCurrentProfile =
5306                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5307                boolean skipCurrentProfileIfNoMatchFound =
5308                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5309                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5310                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5311                    // Checking if there are activities in the target user that can handle the
5312                    // intent.
5313                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5314                            resolvedType, flags, sourceUserId);
5315                    if (resolveInfo != null) return resolveInfo;
5316                    alreadyTriedUserIds.put(targetUserId, true);
5317                }
5318            }
5319        }
5320        return null;
5321    }
5322
5323    /**
5324     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5325     * will forward the intent to the filter's target user.
5326     * Otherwise, returns null.
5327     */
5328    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5329            String resolvedType, int flags, int sourceUserId) {
5330        int targetUserId = filter.getTargetUserId();
5331        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5332                resolvedType, flags, targetUserId);
5333        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5334                && isUserEnabled(targetUserId)) {
5335            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5336        }
5337        return null;
5338    }
5339
5340    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5341            int sourceUserId, int targetUserId) {
5342        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5343        long ident = Binder.clearCallingIdentity();
5344        boolean targetIsProfile;
5345        try {
5346            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5347        } finally {
5348            Binder.restoreCallingIdentity(ident);
5349        }
5350        String className;
5351        if (targetIsProfile) {
5352            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5353        } else {
5354            className = FORWARD_INTENT_TO_PARENT;
5355        }
5356        ComponentName forwardingActivityComponentName = new ComponentName(
5357                mAndroidApplication.packageName, className);
5358        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5359                sourceUserId);
5360        if (!targetIsProfile) {
5361            forwardingActivityInfo.showUserIcon = targetUserId;
5362            forwardingResolveInfo.noResourceId = true;
5363        }
5364        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5365        forwardingResolveInfo.priority = 0;
5366        forwardingResolveInfo.preferredOrder = 0;
5367        forwardingResolveInfo.match = 0;
5368        forwardingResolveInfo.isDefault = true;
5369        forwardingResolveInfo.filter = filter;
5370        forwardingResolveInfo.targetUserId = targetUserId;
5371        return forwardingResolveInfo;
5372    }
5373
5374    @Override
5375    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5376            Intent[] specifics, String[] specificTypes, Intent intent,
5377            String resolvedType, int flags, int userId) {
5378        if (!sUserManager.exists(userId)) return Collections.emptyList();
5379        flags = updateFlagsForResolve(flags, userId, intent);
5380        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5381                false, "query intent activity options");
5382        final String resultsAction = intent.getAction();
5383
5384        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5385                | PackageManager.GET_RESOLVED_FILTER, userId);
5386
5387        if (DEBUG_INTENT_MATCHING) {
5388            Log.v(TAG, "Query " + intent + ": " + results);
5389        }
5390
5391        int specificsPos = 0;
5392        int N;
5393
5394        // todo: note that the algorithm used here is O(N^2).  This
5395        // isn't a problem in our current environment, but if we start running
5396        // into situations where we have more than 5 or 10 matches then this
5397        // should probably be changed to something smarter...
5398
5399        // First we go through and resolve each of the specific items
5400        // that were supplied, taking care of removing any corresponding
5401        // duplicate items in the generic resolve list.
5402        if (specifics != null) {
5403            for (int i=0; i<specifics.length; i++) {
5404                final Intent sintent = specifics[i];
5405                if (sintent == null) {
5406                    continue;
5407                }
5408
5409                if (DEBUG_INTENT_MATCHING) {
5410                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5411                }
5412
5413                String action = sintent.getAction();
5414                if (resultsAction != null && resultsAction.equals(action)) {
5415                    // If this action was explicitly requested, then don't
5416                    // remove things that have it.
5417                    action = null;
5418                }
5419
5420                ResolveInfo ri = null;
5421                ActivityInfo ai = null;
5422
5423                ComponentName comp = sintent.getComponent();
5424                if (comp == null) {
5425                    ri = resolveIntent(
5426                        sintent,
5427                        specificTypes != null ? specificTypes[i] : null,
5428                            flags, userId);
5429                    if (ri == null) {
5430                        continue;
5431                    }
5432                    if (ri == mResolveInfo) {
5433                        // ACK!  Must do something better with this.
5434                    }
5435                    ai = ri.activityInfo;
5436                    comp = new ComponentName(ai.applicationInfo.packageName,
5437                            ai.name);
5438                } else {
5439                    ai = getActivityInfo(comp, flags, userId);
5440                    if (ai == null) {
5441                        continue;
5442                    }
5443                }
5444
5445                // Look for any generic query activities that are duplicates
5446                // of this specific one, and remove them from the results.
5447                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5448                N = results.size();
5449                int j;
5450                for (j=specificsPos; j<N; j++) {
5451                    ResolveInfo sri = results.get(j);
5452                    if ((sri.activityInfo.name.equals(comp.getClassName())
5453                            && sri.activityInfo.applicationInfo.packageName.equals(
5454                                    comp.getPackageName()))
5455                        || (action != null && sri.filter.matchAction(action))) {
5456                        results.remove(j);
5457                        if (DEBUG_INTENT_MATCHING) Log.v(
5458                            TAG, "Removing duplicate item from " + j
5459                            + " due to specific " + specificsPos);
5460                        if (ri == null) {
5461                            ri = sri;
5462                        }
5463                        j--;
5464                        N--;
5465                    }
5466                }
5467
5468                // Add this specific item to its proper place.
5469                if (ri == null) {
5470                    ri = new ResolveInfo();
5471                    ri.activityInfo = ai;
5472                }
5473                results.add(specificsPos, ri);
5474                ri.specificIndex = i;
5475                specificsPos++;
5476            }
5477        }
5478
5479        // Now we go through the remaining generic results and remove any
5480        // duplicate actions that are found here.
5481        N = results.size();
5482        for (int i=specificsPos; i<N-1; i++) {
5483            final ResolveInfo rii = results.get(i);
5484            if (rii.filter == null) {
5485                continue;
5486            }
5487
5488            // Iterate over all of the actions of this result's intent
5489            // filter...  typically this should be just one.
5490            final Iterator<String> it = rii.filter.actionsIterator();
5491            if (it == null) {
5492                continue;
5493            }
5494            while (it.hasNext()) {
5495                final String action = it.next();
5496                if (resultsAction != null && resultsAction.equals(action)) {
5497                    // If this action was explicitly requested, then don't
5498                    // remove things that have it.
5499                    continue;
5500                }
5501                for (int j=i+1; j<N; j++) {
5502                    final ResolveInfo rij = results.get(j);
5503                    if (rij.filter != null && rij.filter.hasAction(action)) {
5504                        results.remove(j);
5505                        if (DEBUG_INTENT_MATCHING) Log.v(
5506                            TAG, "Removing duplicate item from " + j
5507                            + " due to action " + action + " at " + i);
5508                        j--;
5509                        N--;
5510                    }
5511                }
5512            }
5513
5514            // If the caller didn't request filter information, drop it now
5515            // so we don't have to marshall/unmarshall it.
5516            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5517                rii.filter = null;
5518            }
5519        }
5520
5521        // Filter out the caller activity if so requested.
5522        if (caller != null) {
5523            N = results.size();
5524            for (int i=0; i<N; i++) {
5525                ActivityInfo ainfo = results.get(i).activityInfo;
5526                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5527                        && caller.getClassName().equals(ainfo.name)) {
5528                    results.remove(i);
5529                    break;
5530                }
5531            }
5532        }
5533
5534        // If the caller didn't request filter information,
5535        // drop them now so we don't have to
5536        // marshall/unmarshall it.
5537        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5538            N = results.size();
5539            for (int i=0; i<N; i++) {
5540                results.get(i).filter = null;
5541            }
5542        }
5543
5544        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5545        return results;
5546    }
5547
5548    @Override
5549    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5550            int userId) {
5551        if (!sUserManager.exists(userId)) return Collections.emptyList();
5552        flags = updateFlagsForResolve(flags, userId, intent);
5553        ComponentName comp = intent.getComponent();
5554        if (comp == null) {
5555            if (intent.getSelector() != null) {
5556                intent = intent.getSelector();
5557                comp = intent.getComponent();
5558            }
5559        }
5560        if (comp != null) {
5561            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5562            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5563            if (ai != null) {
5564                ResolveInfo ri = new ResolveInfo();
5565                ri.activityInfo = ai;
5566                list.add(ri);
5567            }
5568            return list;
5569        }
5570
5571        // reader
5572        synchronized (mPackages) {
5573            String pkgName = intent.getPackage();
5574            if (pkgName == null) {
5575                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5576            }
5577            final PackageParser.Package pkg = mPackages.get(pkgName);
5578            if (pkg != null) {
5579                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5580                        userId);
5581            }
5582            return null;
5583        }
5584    }
5585
5586    @Override
5587    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5588        if (!sUserManager.exists(userId)) return null;
5589        flags = updateFlagsForResolve(flags, userId, intent);
5590        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5591        if (query != null) {
5592            if (query.size() >= 1) {
5593                // If there is more than one service with the same priority,
5594                // just arbitrarily pick the first one.
5595                return query.get(0);
5596            }
5597        }
5598        return null;
5599    }
5600
5601    @Override
5602    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5603            int userId) {
5604        if (!sUserManager.exists(userId)) return Collections.emptyList();
5605        flags = updateFlagsForResolve(flags, userId, intent);
5606        ComponentName comp = intent.getComponent();
5607        if (comp == null) {
5608            if (intent.getSelector() != null) {
5609                intent = intent.getSelector();
5610                comp = intent.getComponent();
5611            }
5612        }
5613        if (comp != null) {
5614            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5615            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5616            if (si != null) {
5617                final ResolveInfo ri = new ResolveInfo();
5618                ri.serviceInfo = si;
5619                list.add(ri);
5620            }
5621            return list;
5622        }
5623
5624        // reader
5625        synchronized (mPackages) {
5626            String pkgName = intent.getPackage();
5627            if (pkgName == null) {
5628                return mServices.queryIntent(intent, resolvedType, flags, userId);
5629            }
5630            final PackageParser.Package pkg = mPackages.get(pkgName);
5631            if (pkg != null) {
5632                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5633                        userId);
5634            }
5635            return null;
5636        }
5637    }
5638
5639    @Override
5640    public List<ResolveInfo> queryIntentContentProviders(
5641            Intent intent, String resolvedType, int flags, int userId) {
5642        if (!sUserManager.exists(userId)) return Collections.emptyList();
5643        flags = updateFlagsForResolve(flags, userId, intent);
5644        ComponentName comp = intent.getComponent();
5645        if (comp == null) {
5646            if (intent.getSelector() != null) {
5647                intent = intent.getSelector();
5648                comp = intent.getComponent();
5649            }
5650        }
5651        if (comp != null) {
5652            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5653            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5654            if (pi != null) {
5655                final ResolveInfo ri = new ResolveInfo();
5656                ri.providerInfo = pi;
5657                list.add(ri);
5658            }
5659            return list;
5660        }
5661
5662        // reader
5663        synchronized (mPackages) {
5664            String pkgName = intent.getPackage();
5665            if (pkgName == null) {
5666                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5667            }
5668            final PackageParser.Package pkg = mPackages.get(pkgName);
5669            if (pkg != null) {
5670                return mProviders.queryIntentForPackage(
5671                        intent, resolvedType, flags, pkg.providers, userId);
5672            }
5673            return null;
5674        }
5675    }
5676
5677    @Override
5678    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5679        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5680        flags = updateFlagsForPackage(flags, userId, null);
5681        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5682        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5683
5684        // writer
5685        synchronized (mPackages) {
5686            ArrayList<PackageInfo> list;
5687            if (listUninstalled) {
5688                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5689                for (PackageSetting ps : mSettings.mPackages.values()) {
5690                    PackageInfo pi;
5691                    if (ps.pkg != null) {
5692                        pi = generatePackageInfo(ps.pkg, flags, userId);
5693                    } else {
5694                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5695                    }
5696                    if (pi != null) {
5697                        list.add(pi);
5698                    }
5699                }
5700            } else {
5701                list = new ArrayList<PackageInfo>(mPackages.size());
5702                for (PackageParser.Package p : mPackages.values()) {
5703                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5704                    if (pi != null) {
5705                        list.add(pi);
5706                    }
5707                }
5708            }
5709
5710            return new ParceledListSlice<PackageInfo>(list);
5711        }
5712    }
5713
5714    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5715            String[] permissions, boolean[] tmp, int flags, int userId) {
5716        int numMatch = 0;
5717        final PermissionsState permissionsState = ps.getPermissionsState();
5718        for (int i=0; i<permissions.length; i++) {
5719            final String permission = permissions[i];
5720            if (permissionsState.hasPermission(permission, userId)) {
5721                tmp[i] = true;
5722                numMatch++;
5723            } else {
5724                tmp[i] = false;
5725            }
5726        }
5727        if (numMatch == 0) {
5728            return;
5729        }
5730        PackageInfo pi;
5731        if (ps.pkg != null) {
5732            pi = generatePackageInfo(ps.pkg, flags, userId);
5733        } else {
5734            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5735        }
5736        // The above might return null in cases of uninstalled apps or install-state
5737        // skew across users/profiles.
5738        if (pi != null) {
5739            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5740                if (numMatch == permissions.length) {
5741                    pi.requestedPermissions = permissions;
5742                } else {
5743                    pi.requestedPermissions = new String[numMatch];
5744                    numMatch = 0;
5745                    for (int i=0; i<permissions.length; i++) {
5746                        if (tmp[i]) {
5747                            pi.requestedPermissions[numMatch] = permissions[i];
5748                            numMatch++;
5749                        }
5750                    }
5751                }
5752            }
5753            list.add(pi);
5754        }
5755    }
5756
5757    @Override
5758    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5759            String[] permissions, int flags, int userId) {
5760        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5761        flags = updateFlagsForPackage(flags, userId, permissions);
5762        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5763
5764        // writer
5765        synchronized (mPackages) {
5766            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5767            boolean[] tmpBools = new boolean[permissions.length];
5768            if (listUninstalled) {
5769                for (PackageSetting ps : mSettings.mPackages.values()) {
5770                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5771                }
5772            } else {
5773                for (PackageParser.Package pkg : mPackages.values()) {
5774                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5775                    if (ps != null) {
5776                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5777                                userId);
5778                    }
5779                }
5780            }
5781
5782            return new ParceledListSlice<PackageInfo>(list);
5783        }
5784    }
5785
5786    @Override
5787    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5788        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5789        flags = updateFlagsForApplication(flags, userId, null);
5790        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5791
5792        // writer
5793        synchronized (mPackages) {
5794            ArrayList<ApplicationInfo> list;
5795            if (listUninstalled) {
5796                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5797                for (PackageSetting ps : mSettings.mPackages.values()) {
5798                    ApplicationInfo ai;
5799                    if (ps.pkg != null) {
5800                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5801                                ps.readUserState(userId), userId);
5802                    } else {
5803                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5804                    }
5805                    if (ai != null) {
5806                        list.add(ai);
5807                    }
5808                }
5809            } else {
5810                list = new ArrayList<ApplicationInfo>(mPackages.size());
5811                for (PackageParser.Package p : mPackages.values()) {
5812                    if (p.mExtras != null) {
5813                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5814                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5815                        if (ai != null) {
5816                            list.add(ai);
5817                        }
5818                    }
5819                }
5820            }
5821
5822            return new ParceledListSlice<ApplicationInfo>(list);
5823        }
5824    }
5825
5826    @Override
5827    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5828        if (DISABLE_EPHEMERAL_APPS) {
5829            return null;
5830        }
5831
5832        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5833                "getEphemeralApplications");
5834        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5835                "getEphemeralApplications");
5836        synchronized (mPackages) {
5837            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5838                    .getEphemeralApplicationsLPw(userId);
5839            if (ephemeralApps != null) {
5840                return new ParceledListSlice<>(ephemeralApps);
5841            }
5842        }
5843        return null;
5844    }
5845
5846    @Override
5847    public boolean isEphemeralApplication(String packageName, int userId) {
5848        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5849                "isEphemeral");
5850        if (DISABLE_EPHEMERAL_APPS) {
5851            return false;
5852        }
5853
5854        if (!isCallerSameApp(packageName)) {
5855            return false;
5856        }
5857        synchronized (mPackages) {
5858            PackageParser.Package pkg = mPackages.get(packageName);
5859            if (pkg != null) {
5860                return pkg.applicationInfo.isEphemeralApp();
5861            }
5862        }
5863        return false;
5864    }
5865
5866    @Override
5867    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5868        if (DISABLE_EPHEMERAL_APPS) {
5869            return null;
5870        }
5871
5872        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5873                "getCookie");
5874        if (!isCallerSameApp(packageName)) {
5875            return null;
5876        }
5877        synchronized (mPackages) {
5878            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5879                    packageName, userId);
5880        }
5881    }
5882
5883    @Override
5884    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5885        if (DISABLE_EPHEMERAL_APPS) {
5886            return true;
5887        }
5888
5889        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5890                "setCookie");
5891        if (!isCallerSameApp(packageName)) {
5892            return false;
5893        }
5894        synchronized (mPackages) {
5895            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5896                    packageName, cookie, userId);
5897        }
5898    }
5899
5900    @Override
5901    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5902        if (DISABLE_EPHEMERAL_APPS) {
5903            return null;
5904        }
5905
5906        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5907                "getEphemeralApplicationIcon");
5908        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5909                "getEphemeralApplicationIcon");
5910        synchronized (mPackages) {
5911            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5912                    packageName, userId);
5913        }
5914    }
5915
5916    private boolean isCallerSameApp(String packageName) {
5917        PackageParser.Package pkg = mPackages.get(packageName);
5918        return pkg != null
5919                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5920    }
5921
5922    public List<ApplicationInfo> getPersistentApplications(int flags) {
5923        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5924
5925        // reader
5926        synchronized (mPackages) {
5927            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5928            final int userId = UserHandle.getCallingUserId();
5929            while (i.hasNext()) {
5930                final PackageParser.Package p = i.next();
5931                if (p.applicationInfo != null
5932                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5933                        && (!mSafeMode || isSystemApp(p))) {
5934                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5935                    if (ps != null) {
5936                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5937                                ps.readUserState(userId), userId);
5938                        if (ai != null) {
5939                            finalList.add(ai);
5940                        }
5941                    }
5942                }
5943            }
5944        }
5945
5946        return finalList;
5947    }
5948
5949    @Override
5950    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5951        if (!sUserManager.exists(userId)) return null;
5952        flags = updateFlagsForComponent(flags, userId, name);
5953        // reader
5954        synchronized (mPackages) {
5955            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5956            PackageSetting ps = provider != null
5957                    ? mSettings.mPackages.get(provider.owner.packageName)
5958                    : null;
5959            return ps != null
5960                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5961                    ? PackageParser.generateProviderInfo(provider, flags,
5962                            ps.readUserState(userId), userId)
5963                    : null;
5964        }
5965    }
5966
5967    /**
5968     * @deprecated
5969     */
5970    @Deprecated
5971    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5972        // reader
5973        synchronized (mPackages) {
5974            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5975                    .entrySet().iterator();
5976            final int userId = UserHandle.getCallingUserId();
5977            while (i.hasNext()) {
5978                Map.Entry<String, PackageParser.Provider> entry = i.next();
5979                PackageParser.Provider p = entry.getValue();
5980                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5981
5982                if (ps != null && p.syncable
5983                        && (!mSafeMode || (p.info.applicationInfo.flags
5984                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5985                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5986                            ps.readUserState(userId), userId);
5987                    if (info != null) {
5988                        outNames.add(entry.getKey());
5989                        outInfo.add(info);
5990                    }
5991                }
5992            }
5993        }
5994    }
5995
5996    @Override
5997    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5998            int uid, int flags) {
5999        final int userId = processName != null ? UserHandle.getUserId(uid)
6000                : UserHandle.getCallingUserId();
6001        if (!sUserManager.exists(userId)) return null;
6002        flags = updateFlagsForComponent(flags, userId, processName);
6003
6004        ArrayList<ProviderInfo> finalList = null;
6005        // reader
6006        synchronized (mPackages) {
6007            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6008            while (i.hasNext()) {
6009                final PackageParser.Provider p = i.next();
6010                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6011                if (ps != null && p.info.authority != null
6012                        && (processName == null
6013                                || (p.info.processName.equals(processName)
6014                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6015                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6016                    if (finalList == null) {
6017                        finalList = new ArrayList<ProviderInfo>(3);
6018                    }
6019                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6020                            ps.readUserState(userId), userId);
6021                    if (info != null) {
6022                        finalList.add(info);
6023                    }
6024                }
6025            }
6026        }
6027
6028        if (finalList != null) {
6029            Collections.sort(finalList, mProviderInitOrderSorter);
6030            return new ParceledListSlice<ProviderInfo>(finalList);
6031        }
6032
6033        return null;
6034    }
6035
6036    @Override
6037    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6038        // reader
6039        synchronized (mPackages) {
6040            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6041            return PackageParser.generateInstrumentationInfo(i, flags);
6042        }
6043    }
6044
6045    @Override
6046    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6047            int flags) {
6048        ArrayList<InstrumentationInfo> finalList =
6049            new ArrayList<InstrumentationInfo>();
6050
6051        // reader
6052        synchronized (mPackages) {
6053            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6054            while (i.hasNext()) {
6055                final PackageParser.Instrumentation p = i.next();
6056                if (targetPackage == null
6057                        || targetPackage.equals(p.info.targetPackage)) {
6058                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6059                            flags);
6060                    if (ii != null) {
6061                        finalList.add(ii);
6062                    }
6063                }
6064            }
6065        }
6066
6067        return finalList;
6068    }
6069
6070    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6071        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6072        if (overlays == null) {
6073            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6074            return;
6075        }
6076        for (PackageParser.Package opkg : overlays.values()) {
6077            // Not much to do if idmap fails: we already logged the error
6078            // and we certainly don't want to abort installation of pkg simply
6079            // because an overlay didn't fit properly. For these reasons,
6080            // ignore the return value of createIdmapForPackagePairLI.
6081            createIdmapForPackagePairLI(pkg, opkg);
6082        }
6083    }
6084
6085    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6086            PackageParser.Package opkg) {
6087        if (!opkg.mTrustedOverlay) {
6088            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6089                    opkg.baseCodePath + ": overlay not trusted");
6090            return false;
6091        }
6092        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6093        if (overlaySet == null) {
6094            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6095                    opkg.baseCodePath + " but target package has no known overlays");
6096            return false;
6097        }
6098        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6099        // TODO: generate idmap for split APKs
6100        try {
6101            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6102        } catch (InstallerException e) {
6103            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6104                    + opkg.baseCodePath);
6105            return false;
6106        }
6107        PackageParser.Package[] overlayArray =
6108            overlaySet.values().toArray(new PackageParser.Package[0]);
6109        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6110            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6111                return p1.mOverlayPriority - p2.mOverlayPriority;
6112            }
6113        };
6114        Arrays.sort(overlayArray, cmp);
6115
6116        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6117        int i = 0;
6118        for (PackageParser.Package p : overlayArray) {
6119            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6120        }
6121        return true;
6122    }
6123
6124    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6125        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6126        try {
6127            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6128        } finally {
6129            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6130        }
6131    }
6132
6133    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6134        final File[] files = dir.listFiles();
6135        if (ArrayUtils.isEmpty(files)) {
6136            Log.d(TAG, "No files in app dir " + dir);
6137            return;
6138        }
6139
6140        if (DEBUG_PACKAGE_SCANNING) {
6141            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6142                    + " flags=0x" + Integer.toHexString(parseFlags));
6143        }
6144
6145        for (File file : files) {
6146            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6147                    && !PackageInstallerService.isStageName(file.getName());
6148            if (!isPackage) {
6149                // Ignore entries which are not packages
6150                continue;
6151            }
6152            try {
6153                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6154                        scanFlags, currentTime, null);
6155            } catch (PackageManagerException e) {
6156                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6157
6158                // Delete invalid userdata apps
6159                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6160                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6161                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6162                    removeCodePathLI(file);
6163                }
6164            }
6165        }
6166    }
6167
6168    private static File getSettingsProblemFile() {
6169        File dataDir = Environment.getDataDirectory();
6170        File systemDir = new File(dataDir, "system");
6171        File fname = new File(systemDir, "uiderrors.txt");
6172        return fname;
6173    }
6174
6175    static void reportSettingsProblem(int priority, String msg) {
6176        logCriticalInfo(priority, msg);
6177    }
6178
6179    static void logCriticalInfo(int priority, String msg) {
6180        Slog.println(priority, TAG, msg);
6181        EventLogTags.writePmCriticalInfo(msg);
6182        try {
6183            File fname = getSettingsProblemFile();
6184            FileOutputStream out = new FileOutputStream(fname, true);
6185            PrintWriter pw = new FastPrintWriter(out);
6186            SimpleDateFormat formatter = new SimpleDateFormat();
6187            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6188            pw.println(dateString + ": " + msg);
6189            pw.close();
6190            FileUtils.setPermissions(
6191                    fname.toString(),
6192                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6193                    -1, -1);
6194        } catch (java.io.IOException e) {
6195        }
6196    }
6197
6198    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6199            PackageParser.Package pkg, File srcFile, int parseFlags)
6200            throws PackageManagerException {
6201        if (ps != null
6202                && ps.codePath.equals(srcFile)
6203                && ps.timeStamp == srcFile.lastModified()
6204                && !isCompatSignatureUpdateNeeded(pkg)
6205                && !isRecoverSignatureUpdateNeeded(pkg)) {
6206            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6207            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6208            ArraySet<PublicKey> signingKs;
6209            synchronized (mPackages) {
6210                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6211            }
6212            if (ps.signatures.mSignatures != null
6213                    && ps.signatures.mSignatures.length != 0
6214                    && signingKs != null) {
6215                // Optimization: reuse the existing cached certificates
6216                // if the package appears to be unchanged.
6217                pkg.mSignatures = ps.signatures.mSignatures;
6218                pkg.mSigningKeys = signingKs;
6219                return;
6220            }
6221
6222            Slog.w(TAG, "PackageSetting for " + ps.name
6223                    + " is missing signatures.  Collecting certs again to recover them.");
6224        } else {
6225            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6226        }
6227
6228        try {
6229            pp.collectCertificates(pkg, parseFlags);
6230        } catch (PackageParserException e) {
6231            throw PackageManagerException.from(e);
6232        }
6233    }
6234
6235    /**
6236     *  Traces a package scan.
6237     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6238     */
6239    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6240            long currentTime, UserHandle user) throws PackageManagerException {
6241        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6242        try {
6243            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6244        } finally {
6245            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6246        }
6247    }
6248
6249    /**
6250     *  Scans a package and returns the newly parsed package.
6251     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6252     */
6253    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6254            long currentTime, UserHandle user) throws PackageManagerException {
6255        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6256        parseFlags |= mDefParseFlags;
6257        PackageParser pp = new PackageParser();
6258        pp.setSeparateProcesses(mSeparateProcesses);
6259        pp.setOnlyCoreApps(mOnlyCore);
6260        pp.setDisplayMetrics(mMetrics);
6261
6262        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6263            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6264        }
6265
6266        final PackageParser.Package pkg;
6267        try {
6268            pkg = pp.parsePackage(scanFile, parseFlags);
6269        } catch (PackageParserException e) {
6270            throw PackageManagerException.from(e);
6271        }
6272
6273        PackageSetting ps = null;
6274        PackageSetting updatedPkg;
6275        // reader
6276        synchronized (mPackages) {
6277            // Look to see if we already know about this package.
6278            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6279            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6280                // This package has been renamed to its original name.  Let's
6281                // use that.
6282                ps = mSettings.peekPackageLPr(oldName);
6283            }
6284            // If there was no original package, see one for the real package name.
6285            if (ps == null) {
6286                ps = mSettings.peekPackageLPr(pkg.packageName);
6287            }
6288            // Check to see if this package could be hiding/updating a system
6289            // package.  Must look for it either under the original or real
6290            // package name depending on our state.
6291            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6292            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6293        }
6294        boolean updatedPkgBetter = false;
6295        // First check if this is a system package that may involve an update
6296        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6297            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6298            // it needs to drop FLAG_PRIVILEGED.
6299            if (locationIsPrivileged(scanFile)) {
6300                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6301            } else {
6302                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6303            }
6304
6305            if (ps != null && !ps.codePath.equals(scanFile)) {
6306                // The path has changed from what was last scanned...  check the
6307                // version of the new path against what we have stored to determine
6308                // what to do.
6309                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6310                if (pkg.mVersionCode <= ps.versionCode) {
6311                    // The system package has been updated and the code path does not match
6312                    // Ignore entry. Skip it.
6313                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6314                            + " ignored: updated version " + ps.versionCode
6315                            + " better than this " + pkg.mVersionCode);
6316                    if (!updatedPkg.codePath.equals(scanFile)) {
6317                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6318                                + ps.name + " changing from " + updatedPkg.codePathString
6319                                + " to " + scanFile);
6320                        updatedPkg.codePath = scanFile;
6321                        updatedPkg.codePathString = scanFile.toString();
6322                        updatedPkg.resourcePath = scanFile;
6323                        updatedPkg.resourcePathString = scanFile.toString();
6324                    }
6325                    updatedPkg.pkg = pkg;
6326                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6327                            "Package " + ps.name + " at " + scanFile
6328                                    + " ignored: updated version " + ps.versionCode
6329                                    + " better than this " + pkg.mVersionCode);
6330                } else {
6331                    // The current app on the system partition is better than
6332                    // what we have updated to on the data partition; switch
6333                    // back to the system partition version.
6334                    // At this point, its safely assumed that package installation for
6335                    // apps in system partition will go through. If not there won't be a working
6336                    // version of the app
6337                    // writer
6338                    synchronized (mPackages) {
6339                        // Just remove the loaded entries from package lists.
6340                        mPackages.remove(ps.name);
6341                    }
6342
6343                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6344                            + " reverting from " + ps.codePathString
6345                            + ": new version " + pkg.mVersionCode
6346                            + " better than installed " + ps.versionCode);
6347
6348                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6349                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6350                    synchronized (mInstallLock) {
6351                        args.cleanUpResourcesLI();
6352                    }
6353                    synchronized (mPackages) {
6354                        mSettings.enableSystemPackageLPw(ps.name);
6355                    }
6356                    updatedPkgBetter = true;
6357                }
6358            }
6359        }
6360
6361        if (updatedPkg != null) {
6362            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6363            // initially
6364            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6365
6366            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6367            // flag set initially
6368            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6369                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6370            }
6371        }
6372
6373        // Verify certificates against what was last scanned
6374        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6375
6376        /*
6377         * A new system app appeared, but we already had a non-system one of the
6378         * same name installed earlier.
6379         */
6380        boolean shouldHideSystemApp = false;
6381        if (updatedPkg == null && ps != null
6382                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6383            /*
6384             * Check to make sure the signatures match first. If they don't,
6385             * wipe the installed application and its data.
6386             */
6387            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6388                    != PackageManager.SIGNATURE_MATCH) {
6389                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6390                        + " signatures don't match existing userdata copy; removing");
6391                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6392                ps = null;
6393            } else {
6394                /*
6395                 * If the newly-added system app is an older version than the
6396                 * already installed version, hide it. It will be scanned later
6397                 * and re-added like an update.
6398                 */
6399                if (pkg.mVersionCode <= ps.versionCode) {
6400                    shouldHideSystemApp = true;
6401                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6402                            + " but new version " + pkg.mVersionCode + " better than installed "
6403                            + ps.versionCode + "; hiding system");
6404                } else {
6405                    /*
6406                     * The newly found system app is a newer version that the
6407                     * one previously installed. Simply remove the
6408                     * already-installed application and replace it with our own
6409                     * while keeping the application data.
6410                     */
6411                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6412                            + " reverting from " + ps.codePathString + ": new version "
6413                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6414                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6415                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6416                    synchronized (mInstallLock) {
6417                        args.cleanUpResourcesLI();
6418                    }
6419                }
6420            }
6421        }
6422
6423        // The apk is forward locked (not public) if its code and resources
6424        // are kept in different files. (except for app in either system or
6425        // vendor path).
6426        // TODO grab this value from PackageSettings
6427        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6428            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6429                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6430            }
6431        }
6432
6433        // TODO: extend to support forward-locked splits
6434        String resourcePath = null;
6435        String baseResourcePath = null;
6436        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6437            if (ps != null && ps.resourcePathString != null) {
6438                resourcePath = ps.resourcePathString;
6439                baseResourcePath = ps.resourcePathString;
6440            } else {
6441                // Should not happen at all. Just log an error.
6442                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6443            }
6444        } else {
6445            resourcePath = pkg.codePath;
6446            baseResourcePath = pkg.baseCodePath;
6447        }
6448
6449        // Set application objects path explicitly.
6450        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6451        pkg.applicationInfo.setCodePath(pkg.codePath);
6452        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6453        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6454        pkg.applicationInfo.setResourcePath(resourcePath);
6455        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6456        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6457
6458        // Note that we invoke the following method only if we are about to unpack an application
6459        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6460                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6461
6462        /*
6463         * If the system app should be overridden by a previously installed
6464         * data, hide the system app now and let the /data/app scan pick it up
6465         * again.
6466         */
6467        if (shouldHideSystemApp) {
6468            synchronized (mPackages) {
6469                mSettings.disableSystemPackageLPw(pkg.packageName);
6470            }
6471        }
6472
6473        return scannedPkg;
6474    }
6475
6476    private static String fixProcessName(String defProcessName,
6477            String processName, int uid) {
6478        if (processName == null) {
6479            return defProcessName;
6480        }
6481        return processName;
6482    }
6483
6484    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6485            throws PackageManagerException {
6486        if (pkgSetting.signatures.mSignatures != null) {
6487            // Already existing package. Make sure signatures match
6488            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6489                    == PackageManager.SIGNATURE_MATCH;
6490            if (!match) {
6491                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6492                        == PackageManager.SIGNATURE_MATCH;
6493            }
6494            if (!match) {
6495                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6496                        == PackageManager.SIGNATURE_MATCH;
6497            }
6498            if (!match) {
6499                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6500                        + pkg.packageName + " signatures do not match the "
6501                        + "previously installed version; ignoring!");
6502            }
6503        }
6504
6505        // Check for shared user signatures
6506        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6507            // Already existing package. Make sure signatures match
6508            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6509                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6510            if (!match) {
6511                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6512                        == PackageManager.SIGNATURE_MATCH;
6513            }
6514            if (!match) {
6515                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6516                        == PackageManager.SIGNATURE_MATCH;
6517            }
6518            if (!match) {
6519                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6520                        "Package " + pkg.packageName
6521                        + " has no signatures that match those in shared user "
6522                        + pkgSetting.sharedUser.name + "; ignoring!");
6523            }
6524        }
6525    }
6526
6527    /**
6528     * Enforces that only the system UID or root's UID can call a method exposed
6529     * via Binder.
6530     *
6531     * @param message used as message if SecurityException is thrown
6532     * @throws SecurityException if the caller is not system or root
6533     */
6534    private static final void enforceSystemOrRoot(String message) {
6535        final int uid = Binder.getCallingUid();
6536        if (uid != Process.SYSTEM_UID && uid != 0) {
6537            throw new SecurityException(message);
6538        }
6539    }
6540
6541    @Override
6542    public void performFstrimIfNeeded() {
6543        enforceSystemOrRoot("Only the system can request fstrim");
6544
6545        // Before everything else, see whether we need to fstrim.
6546        try {
6547            IMountService ms = PackageHelper.getMountService();
6548            if (ms != null) {
6549                final boolean isUpgrade = isUpgrade();
6550                boolean doTrim = isUpgrade;
6551                if (doTrim) {
6552                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6553                } else {
6554                    final long interval = android.provider.Settings.Global.getLong(
6555                            mContext.getContentResolver(),
6556                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6557                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6558                    if (interval > 0) {
6559                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6560                        if (timeSinceLast > interval) {
6561                            doTrim = true;
6562                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6563                                    + "; running immediately");
6564                        }
6565                    }
6566                }
6567                if (doTrim) {
6568                    if (!isFirstBoot()) {
6569                        try {
6570                            ActivityManagerNative.getDefault().showBootMessage(
6571                                    mContext.getResources().getString(
6572                                            R.string.android_upgrading_fstrim), true);
6573                        } catch (RemoteException e) {
6574                        }
6575                    }
6576                    ms.runMaintenance();
6577                }
6578            } else {
6579                Slog.e(TAG, "Mount service unavailable!");
6580            }
6581        } catch (RemoteException e) {
6582            // Can't happen; MountService is local
6583        }
6584    }
6585
6586    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6587        List<ResolveInfo> ris = null;
6588        try {
6589            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6590                    intent, null, 0, userId);
6591        } catch (RemoteException e) {
6592        }
6593        ArraySet<String> pkgNames = new ArraySet<String>();
6594        if (ris != null) {
6595            for (ResolveInfo ri : ris) {
6596                pkgNames.add(ri.activityInfo.packageName);
6597            }
6598        }
6599        return pkgNames;
6600    }
6601
6602    @Override
6603    public void notifyPackageUse(String packageName) {
6604        synchronized (mPackages) {
6605            PackageParser.Package p = mPackages.get(packageName);
6606            if (p == null) {
6607                return;
6608            }
6609            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6610        }
6611    }
6612
6613    // TODO: this is not used nor needed. Delete it.
6614    @Override
6615    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6616        return performDexOptTraced(packageName, instructionSet, false);
6617    }
6618
6619    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles) {
6620        return performDexOptTraced(packageName, instructionSet, useProfiles);
6621    }
6622
6623    private boolean performDexOptTraced(String packageName, String instructionSet,
6624                boolean useProfiles) {
6625        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6626        try {
6627            return performDexOptInternal(packageName, instructionSet, useProfiles);
6628        } finally {
6629            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6630        }
6631    }
6632
6633    private boolean performDexOptInternal(String packageName, String instructionSet,
6634                boolean useProfiles) {
6635        PackageParser.Package p;
6636        final String targetInstructionSet;
6637        synchronized (mPackages) {
6638            p = mPackages.get(packageName);
6639            if (p == null) {
6640                return false;
6641            }
6642            mPackageUsage.write(false);
6643
6644            targetInstructionSet = instructionSet != null ? instructionSet :
6645                    getPrimaryInstructionSet(p.applicationInfo);
6646            if (!useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6647                // Skip only if we do not use profiles since they might trigger a recompilation.
6648                return false;
6649            }
6650        }
6651        long callingId = Binder.clearCallingIdentity();
6652        try {
6653            synchronized (mInstallLock) {
6654                final String[] instructionSets = new String[] { targetInstructionSet };
6655                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6656                        true /* inclDependencies */, p.volumeUuid, useProfiles);
6657                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6658            }
6659        } finally {
6660            Binder.restoreCallingIdentity(callingId);
6661        }
6662    }
6663
6664    public ArraySet<String> getOptimizablePackages() {
6665        ArraySet<String> pkgs = new ArraySet<String>();
6666        synchronized (mPackages) {
6667            for (PackageParser.Package p : mPackages.values()) {
6668                if (PackageDexOptimizer.canOptimizePackage(p)) {
6669                    pkgs.add(p.packageName);
6670                }
6671            }
6672        }
6673        return pkgs;
6674    }
6675
6676    public void shutdown() {
6677        mPackageUsage.write(true);
6678    }
6679
6680    @Override
6681    public void forceDexOpt(String packageName) {
6682        enforceSystemOrRoot("forceDexOpt");
6683
6684        PackageParser.Package pkg;
6685        synchronized (mPackages) {
6686            pkg = mPackages.get(packageName);
6687            if (pkg == null) {
6688                throw new IllegalArgumentException("Unknown package: " + packageName);
6689            }
6690        }
6691
6692        synchronized (mInstallLock) {
6693            final String[] instructionSets = new String[] {
6694                    getPrimaryInstructionSet(pkg.applicationInfo) };
6695
6696            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6697
6698            // Whoever is calling forceDexOpt wants a fully compiled package.
6699            // Don't use profiles since that may cause compilation to be skipped.
6700            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6701                    true /* inclDependencies */, pkg.volumeUuid, false /* useProfiles */);
6702
6703            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6704            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6705                throw new IllegalStateException("Failed to dexopt: " + res);
6706            }
6707        }
6708    }
6709
6710    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6711        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6712            Slog.w(TAG, "Unable to update from " + oldPkg.name
6713                    + " to " + newPkg.packageName
6714                    + ": old package not in system partition");
6715            return false;
6716        } else if (mPackages.get(oldPkg.name) != null) {
6717            Slog.w(TAG, "Unable to update from " + oldPkg.name
6718                    + " to " + newPkg.packageName
6719                    + ": old package still exists");
6720            return false;
6721        }
6722        return true;
6723    }
6724
6725    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6726            throws PackageManagerException {
6727        // TODO: triage flags as part of 26466827
6728        final int appId = UserHandle.getAppId(uid);
6729        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6730
6731        try {
6732            final int[] users = sUserManager.getUserIds();
6733            for (int user : users) {
6734                mInstaller.createAppData(volumeUuid, packageName, user, flags, appId, seinfo);
6735            }
6736        } catch (InstallerException e) {
6737            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6738                    "Failed to prepare data directory", e);
6739        }
6740    }
6741
6742    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6743        // TODO: triage flags as part of 26466827
6744        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6745
6746        boolean res = true;
6747        final int[] users = sUserManager.getUserIds();
6748        for (int user : users) {
6749            try {
6750                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6751            } catch (InstallerException e) {
6752                Slog.w(TAG, "Failed to delete data directory", e);
6753                res = false;
6754            }
6755        }
6756        return res;
6757    }
6758
6759    void removeCodePathLI(File codePath) {
6760        if (codePath.isDirectory()) {
6761            try {
6762                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6763            } catch (InstallerException e) {
6764                Slog.w(TAG, "Failed to remove code path", e);
6765            }
6766        } else {
6767            codePath.delete();
6768        }
6769    }
6770
6771    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6772        // TODO: triage flags as part of 26466827
6773        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6774
6775        final int[] users = sUserManager.getUserIds();
6776        for (int user : users) {
6777            try {
6778                mInstaller.clearAppData(volumeUuid, packageName, user,
6779                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6780            } catch (InstallerException e) {
6781                Slog.w(TAG, "Failed to delete code cache directory", e);
6782            }
6783        }
6784    }
6785
6786    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6787            PackageParser.Package changingLib) {
6788        if (file.path != null) {
6789            usesLibraryFiles.add(file.path);
6790            return;
6791        }
6792        PackageParser.Package p = mPackages.get(file.apk);
6793        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6794            // If we are doing this while in the middle of updating a library apk,
6795            // then we need to make sure to use that new apk for determining the
6796            // dependencies here.  (We haven't yet finished committing the new apk
6797            // to the package manager state.)
6798            if (p == null || p.packageName.equals(changingLib.packageName)) {
6799                p = changingLib;
6800            }
6801        }
6802        if (p != null) {
6803            usesLibraryFiles.addAll(p.getAllCodePaths());
6804        }
6805    }
6806
6807    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6808            PackageParser.Package changingLib) throws PackageManagerException {
6809        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6810            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6811            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6812            for (int i=0; i<N; i++) {
6813                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6814                if (file == null) {
6815                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6816                            "Package " + pkg.packageName + " requires unavailable shared library "
6817                            + pkg.usesLibraries.get(i) + "; failing!");
6818                }
6819                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6820            }
6821            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6822            for (int i=0; i<N; i++) {
6823                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6824                if (file == null) {
6825                    Slog.w(TAG, "Package " + pkg.packageName
6826                            + " desires unavailable shared library "
6827                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6828                } else {
6829                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6830                }
6831            }
6832            N = usesLibraryFiles.size();
6833            if (N > 0) {
6834                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6835            } else {
6836                pkg.usesLibraryFiles = null;
6837            }
6838        }
6839    }
6840
6841    private static boolean hasString(List<String> list, List<String> which) {
6842        if (list == null) {
6843            return false;
6844        }
6845        for (int i=list.size()-1; i>=0; i--) {
6846            for (int j=which.size()-1; j>=0; j--) {
6847                if (which.get(j).equals(list.get(i))) {
6848                    return true;
6849                }
6850            }
6851        }
6852        return false;
6853    }
6854
6855    private void updateAllSharedLibrariesLPw() {
6856        for (PackageParser.Package pkg : mPackages.values()) {
6857            try {
6858                updateSharedLibrariesLPw(pkg, null);
6859            } catch (PackageManagerException e) {
6860                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6861            }
6862        }
6863    }
6864
6865    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6866            PackageParser.Package changingPkg) {
6867        ArrayList<PackageParser.Package> res = null;
6868        for (PackageParser.Package pkg : mPackages.values()) {
6869            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6870                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6871                if (res == null) {
6872                    res = new ArrayList<PackageParser.Package>();
6873                }
6874                res.add(pkg);
6875                try {
6876                    updateSharedLibrariesLPw(pkg, changingPkg);
6877                } catch (PackageManagerException e) {
6878                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6879                }
6880            }
6881        }
6882        return res;
6883    }
6884
6885    /**
6886     * Derive the value of the {@code cpuAbiOverride} based on the provided
6887     * value and an optional stored value from the package settings.
6888     */
6889    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6890        String cpuAbiOverride = null;
6891
6892        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6893            cpuAbiOverride = null;
6894        } else if (abiOverride != null) {
6895            cpuAbiOverride = abiOverride;
6896        } else if (settings != null) {
6897            cpuAbiOverride = settings.cpuAbiOverrideString;
6898        }
6899
6900        return cpuAbiOverride;
6901    }
6902
6903    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6904            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6905        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6906        try {
6907            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6908        } finally {
6909            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6910        }
6911    }
6912
6913    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6914            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6915        boolean success = false;
6916        try {
6917            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6918                    currentTime, user);
6919            success = true;
6920            return res;
6921        } finally {
6922            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6923                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6924            }
6925        }
6926    }
6927
6928    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6929            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6930        final File scanFile = new File(pkg.codePath);
6931        if (pkg.applicationInfo.getCodePath() == null ||
6932                pkg.applicationInfo.getResourcePath() == null) {
6933            // Bail out. The resource and code paths haven't been set.
6934            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6935                    "Code and resource paths haven't been set correctly");
6936        }
6937
6938        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6939            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6940        } else {
6941            // Only allow system apps to be flagged as core apps.
6942            pkg.coreApp = false;
6943        }
6944
6945        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6946            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6947        }
6948
6949        if (mCustomResolverComponentName != null &&
6950                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6951            setUpCustomResolverActivity(pkg);
6952        }
6953
6954        if (pkg.packageName.equals("android")) {
6955            synchronized (mPackages) {
6956                if (mAndroidApplication != null) {
6957                    Slog.w(TAG, "*************************************************");
6958                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6959                    Slog.w(TAG, " file=" + scanFile);
6960                    Slog.w(TAG, "*************************************************");
6961                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6962                            "Core android package being redefined.  Skipping.");
6963                }
6964
6965                // Set up information for our fall-back user intent resolution activity.
6966                mPlatformPackage = pkg;
6967                pkg.mVersionCode = mSdkVersion;
6968                mAndroidApplication = pkg.applicationInfo;
6969
6970                if (!mResolverReplaced) {
6971                    mResolveActivity.applicationInfo = mAndroidApplication;
6972                    mResolveActivity.name = ResolverActivity.class.getName();
6973                    mResolveActivity.packageName = mAndroidApplication.packageName;
6974                    mResolveActivity.processName = "system:ui";
6975                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6976                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6977                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6978                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6979                    mResolveActivity.exported = true;
6980                    mResolveActivity.enabled = true;
6981                    mResolveInfo.activityInfo = mResolveActivity;
6982                    mResolveInfo.priority = 0;
6983                    mResolveInfo.preferredOrder = 0;
6984                    mResolveInfo.match = 0;
6985                    mResolveComponentName = new ComponentName(
6986                            mAndroidApplication.packageName, mResolveActivity.name);
6987                }
6988            }
6989        }
6990
6991        if (DEBUG_PACKAGE_SCANNING) {
6992            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6993                Log.d(TAG, "Scanning package " + pkg.packageName);
6994        }
6995
6996        if (mPackages.containsKey(pkg.packageName)
6997                || mSharedLibraries.containsKey(pkg.packageName)) {
6998            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6999                    "Application package " + pkg.packageName
7000                    + " already installed.  Skipping duplicate.");
7001        }
7002
7003        // If we're only installing presumed-existing packages, require that the
7004        // scanned APK is both already known and at the path previously established
7005        // for it.  Previously unknown packages we pick up normally, but if we have an
7006        // a priori expectation about this package's install presence, enforce it.
7007        // With a singular exception for new system packages. When an OTA contains
7008        // a new system package, we allow the codepath to change from a system location
7009        // to the user-installed location. If we don't allow this change, any newer,
7010        // user-installed version of the application will be ignored.
7011        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7012            if (mExpectingBetter.containsKey(pkg.packageName)) {
7013                logCriticalInfo(Log.WARN,
7014                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7015            } else {
7016                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7017                if (known != null) {
7018                    if (DEBUG_PACKAGE_SCANNING) {
7019                        Log.d(TAG, "Examining " + pkg.codePath
7020                                + " and requiring known paths " + known.codePathString
7021                                + " & " + known.resourcePathString);
7022                    }
7023                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7024                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7025                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7026                                "Application package " + pkg.packageName
7027                                + " found at " + pkg.applicationInfo.getCodePath()
7028                                + " but expected at " + known.codePathString + "; ignoring.");
7029                    }
7030                }
7031            }
7032        }
7033
7034        // Initialize package source and resource directories
7035        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7036        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7037
7038        SharedUserSetting suid = null;
7039        PackageSetting pkgSetting = null;
7040
7041        if (!isSystemApp(pkg)) {
7042            // Only system apps can use these features.
7043            pkg.mOriginalPackages = null;
7044            pkg.mRealPackage = null;
7045            pkg.mAdoptPermissions = null;
7046        }
7047
7048        // writer
7049        synchronized (mPackages) {
7050            if (pkg.mSharedUserId != null) {
7051                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7052                if (suid == null) {
7053                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7054                            "Creating application package " + pkg.packageName
7055                            + " for shared user failed");
7056                }
7057                if (DEBUG_PACKAGE_SCANNING) {
7058                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7059                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7060                                + "): packages=" + suid.packages);
7061                }
7062            }
7063
7064            // Check if we are renaming from an original package name.
7065            PackageSetting origPackage = null;
7066            String realName = null;
7067            if (pkg.mOriginalPackages != null) {
7068                // This package may need to be renamed to a previously
7069                // installed name.  Let's check on that...
7070                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7071                if (pkg.mOriginalPackages.contains(renamed)) {
7072                    // This package had originally been installed as the
7073                    // original name, and we have already taken care of
7074                    // transitioning to the new one.  Just update the new
7075                    // one to continue using the old name.
7076                    realName = pkg.mRealPackage;
7077                    if (!pkg.packageName.equals(renamed)) {
7078                        // Callers into this function may have already taken
7079                        // care of renaming the package; only do it here if
7080                        // it is not already done.
7081                        pkg.setPackageName(renamed);
7082                    }
7083
7084                } else {
7085                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7086                        if ((origPackage = mSettings.peekPackageLPr(
7087                                pkg.mOriginalPackages.get(i))) != null) {
7088                            // We do have the package already installed under its
7089                            // original name...  should we use it?
7090                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7091                                // New package is not compatible with original.
7092                                origPackage = null;
7093                                continue;
7094                            } else if (origPackage.sharedUser != null) {
7095                                // Make sure uid is compatible between packages.
7096                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7097                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7098                                            + " to " + pkg.packageName + ": old uid "
7099                                            + origPackage.sharedUser.name
7100                                            + " differs from " + pkg.mSharedUserId);
7101                                    origPackage = null;
7102                                    continue;
7103                                }
7104                            } else {
7105                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7106                                        + pkg.packageName + " to old name " + origPackage.name);
7107                            }
7108                            break;
7109                        }
7110                    }
7111                }
7112            }
7113
7114            if (mTransferedPackages.contains(pkg.packageName)) {
7115                Slog.w(TAG, "Package " + pkg.packageName
7116                        + " was transferred to another, but its .apk remains");
7117            }
7118
7119            // Just create the setting, don't add it yet. For already existing packages
7120            // the PkgSetting exists already and doesn't have to be created.
7121            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7122                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7123                    pkg.applicationInfo.primaryCpuAbi,
7124                    pkg.applicationInfo.secondaryCpuAbi,
7125                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7126                    user, false);
7127            if (pkgSetting == null) {
7128                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7129                        "Creating application package " + pkg.packageName + " failed");
7130            }
7131
7132            if (pkgSetting.origPackage != null) {
7133                // If we are first transitioning from an original package,
7134                // fix up the new package's name now.  We need to do this after
7135                // looking up the package under its new name, so getPackageLP
7136                // can take care of fiddling things correctly.
7137                pkg.setPackageName(origPackage.name);
7138
7139                // File a report about this.
7140                String msg = "New package " + pkgSetting.realName
7141                        + " renamed to replace old package " + pkgSetting.name;
7142                reportSettingsProblem(Log.WARN, msg);
7143
7144                // Make a note of it.
7145                mTransferedPackages.add(origPackage.name);
7146
7147                // No longer need to retain this.
7148                pkgSetting.origPackage = null;
7149            }
7150
7151            if (realName != null) {
7152                // Make a note of it.
7153                mTransferedPackages.add(pkg.packageName);
7154            }
7155
7156            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7157                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7158            }
7159
7160            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7161                // Check all shared libraries and map to their actual file path.
7162                // We only do this here for apps not on a system dir, because those
7163                // are the only ones that can fail an install due to this.  We
7164                // will take care of the system apps by updating all of their
7165                // library paths after the scan is done.
7166                updateSharedLibrariesLPw(pkg, null);
7167            }
7168
7169            if (mFoundPolicyFile) {
7170                SELinuxMMAC.assignSeinfoValue(pkg);
7171            }
7172
7173            pkg.applicationInfo.uid = pkgSetting.appId;
7174            pkg.mExtras = pkgSetting;
7175            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7176                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7177                    // We just determined the app is signed correctly, so bring
7178                    // over the latest parsed certs.
7179                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7180                } else {
7181                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7182                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7183                                "Package " + pkg.packageName + " upgrade keys do not match the "
7184                                + "previously installed version");
7185                    } else {
7186                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7187                        String msg = "System package " + pkg.packageName
7188                            + " signature changed; retaining data.";
7189                        reportSettingsProblem(Log.WARN, msg);
7190                    }
7191                }
7192            } else {
7193                try {
7194                    verifySignaturesLP(pkgSetting, pkg);
7195                    // We just determined the app is signed correctly, so bring
7196                    // over the latest parsed certs.
7197                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7198                } catch (PackageManagerException e) {
7199                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7200                        throw e;
7201                    }
7202                    // The signature has changed, but this package is in the system
7203                    // image...  let's recover!
7204                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7205                    // However...  if this package is part of a shared user, but it
7206                    // doesn't match the signature of the shared user, let's fail.
7207                    // What this means is that you can't change the signatures
7208                    // associated with an overall shared user, which doesn't seem all
7209                    // that unreasonable.
7210                    if (pkgSetting.sharedUser != null) {
7211                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7212                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7213                            throw new PackageManagerException(
7214                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7215                                            "Signature mismatch for shared user: "
7216                                            + pkgSetting.sharedUser);
7217                        }
7218                    }
7219                    // File a report about this.
7220                    String msg = "System package " + pkg.packageName
7221                        + " signature changed; retaining data.";
7222                    reportSettingsProblem(Log.WARN, msg);
7223                }
7224            }
7225            // Verify that this new package doesn't have any content providers
7226            // that conflict with existing packages.  Only do this if the
7227            // package isn't already installed, since we don't want to break
7228            // things that are installed.
7229            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7230                final int N = pkg.providers.size();
7231                int i;
7232                for (i=0; i<N; i++) {
7233                    PackageParser.Provider p = pkg.providers.get(i);
7234                    if (p.info.authority != null) {
7235                        String names[] = p.info.authority.split(";");
7236                        for (int j = 0; j < names.length; j++) {
7237                            if (mProvidersByAuthority.containsKey(names[j])) {
7238                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7239                                final String otherPackageName =
7240                                        ((other != null && other.getComponentName() != null) ?
7241                                                other.getComponentName().getPackageName() : "?");
7242                                throw new PackageManagerException(
7243                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7244                                                "Can't install because provider name " + names[j]
7245                                                + " (in package " + pkg.applicationInfo.packageName
7246                                                + ") is already used by " + otherPackageName);
7247                            }
7248                        }
7249                    }
7250                }
7251            }
7252
7253            if (pkg.mAdoptPermissions != null) {
7254                // This package wants to adopt ownership of permissions from
7255                // another package.
7256                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7257                    final String origName = pkg.mAdoptPermissions.get(i);
7258                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7259                    if (orig != null) {
7260                        if (verifyPackageUpdateLPr(orig, pkg)) {
7261                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7262                                    + pkg.packageName);
7263                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7264                        }
7265                    }
7266                }
7267            }
7268        }
7269
7270        final String pkgName = pkg.packageName;
7271
7272        final long scanFileTime = scanFile.lastModified();
7273        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7274        pkg.applicationInfo.processName = fixProcessName(
7275                pkg.applicationInfo.packageName,
7276                pkg.applicationInfo.processName,
7277                pkg.applicationInfo.uid);
7278
7279        if (pkg != mPlatformPackage) {
7280            // This is a normal package, need to make its data directory.
7281            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7282                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7283
7284            // TOOD: switch to ensure various directories
7285
7286            boolean uidError = false;
7287            if (dataPath.exists()) {
7288                int currentUid = 0;
7289                try {
7290                    StructStat stat = Os.stat(dataPath.getPath());
7291                    currentUid = stat.st_uid;
7292                } catch (ErrnoException e) {
7293                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7294                }
7295
7296                // If we have mismatched owners for the data path, we have a problem.
7297                if (currentUid != pkg.applicationInfo.uid) {
7298                    boolean recovered = false;
7299                    if (((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0
7300                            || (scanFlags & SCAN_BOOTING) != 0)) {
7301                        // If this is a system app, we can at least delete its
7302                        // current data so the application will still work.
7303                        boolean res = removeDataDirsLI(pkg.volumeUuid, pkgName);
7304                        if (res) {
7305                            // TODO: Kill the processes first
7306                            // Old data gone!
7307                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7308                                    ? "System package " : "Third party package ";
7309                            String msg = prefix + pkg.packageName
7310                                    + " has changed from uid: "
7311                                    + currentUid + " to "
7312                                    + pkg.applicationInfo.uid + "; old data erased";
7313                            reportSettingsProblem(Log.WARN, msg);
7314                            recovered = true;
7315                        }
7316                        if (!recovered) {
7317                            mHasSystemUidErrors = true;
7318                        }
7319                    } else {
7320                        // If we allow this install to proceed, we will be broken.
7321                        // Abort, abort!
7322                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7323                                "Expected data to be owned by UID " + pkg.applicationInfo.uid
7324                                        + " but found " + currentUid);
7325                    }
7326                    if (!recovered) {
7327                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7328                            + pkg.applicationInfo.uid + "/fs_"
7329                            + currentUid;
7330                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7331                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7332                        String msg = "Package " + pkg.packageName
7333                                + " has mismatched uid: "
7334                                + currentUid + " on disk, "
7335                                + pkg.applicationInfo.uid + " in settings";
7336                        // writer
7337                        synchronized (mPackages) {
7338                            mSettings.mReadMessages.append(msg);
7339                            mSettings.mReadMessages.append('\n');
7340                            uidError = true;
7341                            if (!pkgSetting.uidError) {
7342                                reportSettingsProblem(Log.ERROR, msg);
7343                            }
7344                        }
7345                    }
7346                }
7347
7348                // Ensure that directories are prepared
7349                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7350                        pkg.applicationInfo.seinfo);
7351
7352                if (mShouldRestoreconData) {
7353                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7354                    // TODO: extend this to restorecon over all users
7355                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
7356                    // TODO: triage flags as part of 26466827
7357                    final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
7358                    try {
7359                        mInstaller.restoreconAppData(pkg.volumeUuid, pkg.packageName,
7360                                UserHandle.USER_SYSTEM, flags, appId, pkg.applicationInfo.seinfo);
7361                    } catch (InstallerException e) {
7362                        Slog.w(TAG, "Failed to restorecon " + pkg.packageName, e);
7363                    }
7364                }
7365            } else {
7366                if (DEBUG_PACKAGE_SCANNING) {
7367                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7368                        Log.v(TAG, "Want this data dir: " + dataPath);
7369                }
7370                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7371                        pkg.applicationInfo.seinfo);
7372            }
7373
7374            // Get all of our default paths setup
7375            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7376
7377            pkgSetting.uidError = uidError;
7378        }
7379
7380        final String path = scanFile.getPath();
7381        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7382
7383        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7384            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7385
7386            // Some system apps still use directory structure for native libraries
7387            // in which case we might end up not detecting abi solely based on apk
7388            // structure. Try to detect abi based on directory structure.
7389            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7390                    pkg.applicationInfo.primaryCpuAbi == null) {
7391                setBundledAppAbisAndRoots(pkg, pkgSetting);
7392                setNativeLibraryPaths(pkg);
7393            }
7394
7395        } else {
7396            if ((scanFlags & SCAN_MOVE) != 0) {
7397                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7398                // but we already have this packages package info in the PackageSetting. We just
7399                // use that and derive the native library path based on the new codepath.
7400                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7401                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7402            }
7403
7404            // Set native library paths again. For moves, the path will be updated based on the
7405            // ABIs we've determined above. For non-moves, the path will be updated based on the
7406            // ABIs we determined during compilation, but the path will depend on the final
7407            // package path (after the rename away from the stage path).
7408            setNativeLibraryPaths(pkg);
7409        }
7410
7411        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7412        final int[] userIds = sUserManager.getUserIds();
7413        synchronized (mInstallLock) {
7414            // Make sure all user data directories are ready to roll; we're okay
7415            // if they already exist
7416            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7417                for (int userId : userIds) {
7418                    if (userId != UserHandle.USER_SYSTEM) {
7419                        // TODO: triage flags as part of 26466827
7420                        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
7421                        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
7422                        try {
7423                            mInstaller.createAppData(pkg.volumeUuid, pkg.packageName, userId,
7424                                    flags, appId, pkg.applicationInfo.seinfo);
7425                        } catch (InstallerException e) {
7426                            throw PackageManagerException.from(e);
7427                        }
7428                    }
7429                }
7430            }
7431
7432            // Create a native library symlink only if we have native libraries
7433            // and if the native libraries are 32 bit libraries. We do not provide
7434            // this symlink for 64 bit libraries.
7435            if (pkg.applicationInfo.primaryCpuAbi != null &&
7436                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7437                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7438                try {
7439                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7440                    for (int userId : userIds) {
7441                        try {
7442                            mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7443                                    nativeLibPath, userId);
7444                        } catch (InstallerException e) {
7445                            throw PackageManagerException.from(e);
7446                        }
7447                    }
7448                } finally {
7449                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7450                }
7451            }
7452        }
7453
7454        // This is a special case for the "system" package, where the ABI is
7455        // dictated by the zygote configuration (and init.rc). We should keep track
7456        // of this ABI so that we can deal with "normal" applications that run under
7457        // the same UID correctly.
7458        if (mPlatformPackage == pkg) {
7459            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7460                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7461        }
7462
7463        // If there's a mismatch between the abi-override in the package setting
7464        // and the abiOverride specified for the install. Warn about this because we
7465        // would've already compiled the app without taking the package setting into
7466        // account.
7467        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7468            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7469                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7470                        " for package " + pkg.packageName);
7471            }
7472        }
7473
7474        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7475        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7476        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7477
7478        // Copy the derived override back to the parsed package, so that we can
7479        // update the package settings accordingly.
7480        pkg.cpuAbiOverride = cpuAbiOverride;
7481
7482        if (DEBUG_ABI_SELECTION) {
7483            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7484                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7485                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7486        }
7487
7488        // Push the derived path down into PackageSettings so we know what to
7489        // clean up at uninstall time.
7490        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7491
7492        if (DEBUG_ABI_SELECTION) {
7493            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7494                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7495                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7496        }
7497
7498        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7499            // We don't do this here during boot because we can do it all
7500            // at once after scanning all existing packages.
7501            //
7502            // We also do this *before* we perform dexopt on this package, so that
7503            // we can avoid redundant dexopts, and also to make sure we've got the
7504            // code and package path correct.
7505            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7506                    pkg, true /* boot complete */);
7507        }
7508
7509        if (mFactoryTest && pkg.requestedPermissions.contains(
7510                android.Manifest.permission.FACTORY_TEST)) {
7511            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7512        }
7513
7514        ArrayList<PackageParser.Package> clientLibPkgs = null;
7515
7516        // writer
7517        synchronized (mPackages) {
7518            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7519                // Only system apps can add new shared libraries.
7520                if (pkg.libraryNames != null) {
7521                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7522                        String name = pkg.libraryNames.get(i);
7523                        boolean allowed = false;
7524                        if (pkg.isUpdatedSystemApp()) {
7525                            // New library entries can only be added through the
7526                            // system image.  This is important to get rid of a lot
7527                            // of nasty edge cases: for example if we allowed a non-
7528                            // system update of the app to add a library, then uninstalling
7529                            // the update would make the library go away, and assumptions
7530                            // we made such as through app install filtering would now
7531                            // have allowed apps on the device which aren't compatible
7532                            // with it.  Better to just have the restriction here, be
7533                            // conservative, and create many fewer cases that can negatively
7534                            // impact the user experience.
7535                            final PackageSetting sysPs = mSettings
7536                                    .getDisabledSystemPkgLPr(pkg.packageName);
7537                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7538                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7539                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7540                                        allowed = true;
7541                                        break;
7542                                    }
7543                                }
7544                            }
7545                        } else {
7546                            allowed = true;
7547                        }
7548                        if (allowed) {
7549                            if (!mSharedLibraries.containsKey(name)) {
7550                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7551                            } else if (!name.equals(pkg.packageName)) {
7552                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7553                                        + name + " already exists; skipping");
7554                            }
7555                        } else {
7556                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7557                                    + name + " that is not declared on system image; skipping");
7558                        }
7559                    }
7560                    if ((scanFlags & SCAN_BOOTING) == 0) {
7561                        // If we are not booting, we need to update any applications
7562                        // that are clients of our shared library.  If we are booting,
7563                        // this will all be done once the scan is complete.
7564                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7565                    }
7566                }
7567            }
7568        }
7569
7570        // Request the ActivityManager to kill the process(only for existing packages)
7571        // so that we do not end up in a confused state while the user is still using the older
7572        // version of the application while the new one gets installed.
7573        if ((scanFlags & SCAN_REPLACING) != 0) {
7574            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7575
7576            killApplication(pkg.applicationInfo.packageName,
7577                        pkg.applicationInfo.uid, "replace pkg");
7578
7579            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7580        }
7581
7582        // Also need to kill any apps that are dependent on the library.
7583        if (clientLibPkgs != null) {
7584            for (int i=0; i<clientLibPkgs.size(); i++) {
7585                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7586                killApplication(clientPkg.applicationInfo.packageName,
7587                        clientPkg.applicationInfo.uid, "update lib");
7588            }
7589        }
7590
7591        // Make sure we're not adding any bogus keyset info
7592        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7593        ksms.assertScannedPackageValid(pkg);
7594
7595        // writer
7596        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7597
7598        boolean createIdmapFailed = false;
7599        synchronized (mPackages) {
7600            // We don't expect installation to fail beyond this point
7601
7602            // Add the new setting to mSettings
7603            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7604            // Add the new setting to mPackages
7605            mPackages.put(pkg.applicationInfo.packageName, pkg);
7606            // Make sure we don't accidentally delete its data.
7607            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7608            while (iter.hasNext()) {
7609                PackageCleanItem item = iter.next();
7610                if (pkgName.equals(item.packageName)) {
7611                    iter.remove();
7612                }
7613            }
7614
7615            // Take care of first install / last update times.
7616            if (currentTime != 0) {
7617                if (pkgSetting.firstInstallTime == 0) {
7618                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7619                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7620                    pkgSetting.lastUpdateTime = currentTime;
7621                }
7622            } else if (pkgSetting.firstInstallTime == 0) {
7623                // We need *something*.  Take time time stamp of the file.
7624                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7625            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7626                if (scanFileTime != pkgSetting.timeStamp) {
7627                    // A package on the system image has changed; consider this
7628                    // to be an update.
7629                    pkgSetting.lastUpdateTime = scanFileTime;
7630                }
7631            }
7632
7633            // Add the package's KeySets to the global KeySetManagerService
7634            ksms.addScannedPackageLPw(pkg);
7635
7636            int N = pkg.providers.size();
7637            StringBuilder r = null;
7638            int i;
7639            for (i=0; i<N; i++) {
7640                PackageParser.Provider p = pkg.providers.get(i);
7641                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7642                        p.info.processName, pkg.applicationInfo.uid);
7643                mProviders.addProvider(p);
7644                p.syncable = p.info.isSyncable;
7645                if (p.info.authority != null) {
7646                    String names[] = p.info.authority.split(";");
7647                    p.info.authority = null;
7648                    for (int j = 0; j < names.length; j++) {
7649                        if (j == 1 && p.syncable) {
7650                            // We only want the first authority for a provider to possibly be
7651                            // syncable, so if we already added this provider using a different
7652                            // authority clear the syncable flag. We copy the provider before
7653                            // changing it because the mProviders object contains a reference
7654                            // to a provider that we don't want to change.
7655                            // Only do this for the second authority since the resulting provider
7656                            // object can be the same for all future authorities for this provider.
7657                            p = new PackageParser.Provider(p);
7658                            p.syncable = false;
7659                        }
7660                        if (!mProvidersByAuthority.containsKey(names[j])) {
7661                            mProvidersByAuthority.put(names[j], p);
7662                            if (p.info.authority == null) {
7663                                p.info.authority = names[j];
7664                            } else {
7665                                p.info.authority = p.info.authority + ";" + names[j];
7666                            }
7667                            if (DEBUG_PACKAGE_SCANNING) {
7668                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7669                                    Log.d(TAG, "Registered content provider: " + names[j]
7670                                            + ", className = " + p.info.name + ", isSyncable = "
7671                                            + p.info.isSyncable);
7672                            }
7673                        } else {
7674                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7675                            Slog.w(TAG, "Skipping provider name " + names[j] +
7676                                    " (in package " + pkg.applicationInfo.packageName +
7677                                    "): name already used by "
7678                                    + ((other != null && other.getComponentName() != null)
7679                                            ? other.getComponentName().getPackageName() : "?"));
7680                        }
7681                    }
7682                }
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(p.info.name);
7690                }
7691            }
7692            if (r != null) {
7693                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7694            }
7695
7696            N = pkg.services.size();
7697            r = null;
7698            for (i=0; i<N; i++) {
7699                PackageParser.Service s = pkg.services.get(i);
7700                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7701                        s.info.processName, pkg.applicationInfo.uid);
7702                mServices.addService(s);
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(s.info.name);
7710                }
7711            }
7712            if (r != null) {
7713                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7714            }
7715
7716            N = pkg.receivers.size();
7717            r = null;
7718            for (i=0; i<N; i++) {
7719                PackageParser.Activity a = pkg.receivers.get(i);
7720                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7721                        a.info.processName, pkg.applicationInfo.uid);
7722                mReceivers.addActivity(a, "receiver");
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(a.info.name);
7730                }
7731            }
7732            if (r != null) {
7733                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7734            }
7735
7736            N = pkg.activities.size();
7737            r = null;
7738            for (i=0; i<N; i++) {
7739                PackageParser.Activity a = pkg.activities.get(i);
7740                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7741                        a.info.processName, pkg.applicationInfo.uid);
7742                mActivities.addActivity(a, "activity");
7743                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7744                    if (r == null) {
7745                        r = new StringBuilder(256);
7746                    } else {
7747                        r.append(' ');
7748                    }
7749                    r.append(a.info.name);
7750                }
7751            }
7752            if (r != null) {
7753                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7754            }
7755
7756            N = pkg.permissionGroups.size();
7757            r = null;
7758            for (i=0; i<N; i++) {
7759                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7760                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7761                if (cur == null) {
7762                    mPermissionGroups.put(pg.info.name, pg);
7763                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7764                        if (r == null) {
7765                            r = new StringBuilder(256);
7766                        } else {
7767                            r.append(' ');
7768                        }
7769                        r.append(pg.info.name);
7770                    }
7771                } else {
7772                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7773                            + pg.info.packageName + " ignored: original from "
7774                            + cur.info.packageName);
7775                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7776                        if (r == null) {
7777                            r = new StringBuilder(256);
7778                        } else {
7779                            r.append(' ');
7780                        }
7781                        r.append("DUP:");
7782                        r.append(pg.info.name);
7783                    }
7784                }
7785            }
7786            if (r != null) {
7787                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7788            }
7789
7790            N = pkg.permissions.size();
7791            r = null;
7792            for (i=0; i<N; i++) {
7793                PackageParser.Permission p = pkg.permissions.get(i);
7794
7795                // Assume by default that we did not install this permission into the system.
7796                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7797
7798                // Now that permission groups have a special meaning, we ignore permission
7799                // groups for legacy apps to prevent unexpected behavior. In particular,
7800                // permissions for one app being granted to someone just becuase they happen
7801                // to be in a group defined by another app (before this had no implications).
7802                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7803                    p.group = mPermissionGroups.get(p.info.group);
7804                    // Warn for a permission in an unknown group.
7805                    if (p.info.group != null && p.group == null) {
7806                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7807                                + p.info.packageName + " in an unknown group " + p.info.group);
7808                    }
7809                }
7810
7811                ArrayMap<String, BasePermission> permissionMap =
7812                        p.tree ? mSettings.mPermissionTrees
7813                                : mSettings.mPermissions;
7814                BasePermission bp = permissionMap.get(p.info.name);
7815
7816                // Allow system apps to redefine non-system permissions
7817                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7818                    final boolean currentOwnerIsSystem = (bp.perm != null
7819                            && isSystemApp(bp.perm.owner));
7820                    if (isSystemApp(p.owner)) {
7821                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7822                            // It's a built-in permission and no owner, take ownership now
7823                            bp.packageSetting = pkgSetting;
7824                            bp.perm = p;
7825                            bp.uid = pkg.applicationInfo.uid;
7826                            bp.sourcePackage = p.info.packageName;
7827                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7828                        } else if (!currentOwnerIsSystem) {
7829                            String msg = "New decl " + p.owner + " of permission  "
7830                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7831                            reportSettingsProblem(Log.WARN, msg);
7832                            bp = null;
7833                        }
7834                    }
7835                }
7836
7837                if (bp == null) {
7838                    bp = new BasePermission(p.info.name, p.info.packageName,
7839                            BasePermission.TYPE_NORMAL);
7840                    permissionMap.put(p.info.name, bp);
7841                }
7842
7843                if (bp.perm == null) {
7844                    if (bp.sourcePackage == null
7845                            || bp.sourcePackage.equals(p.info.packageName)) {
7846                        BasePermission tree = findPermissionTreeLP(p.info.name);
7847                        if (tree == null
7848                                || tree.sourcePackage.equals(p.info.packageName)) {
7849                            bp.packageSetting = pkgSetting;
7850                            bp.perm = p;
7851                            bp.uid = pkg.applicationInfo.uid;
7852                            bp.sourcePackage = p.info.packageName;
7853                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7854                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7855                                if (r == null) {
7856                                    r = new StringBuilder(256);
7857                                } else {
7858                                    r.append(' ');
7859                                }
7860                                r.append(p.info.name);
7861                            }
7862                        } else {
7863                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7864                                    + p.info.packageName + " ignored: base tree "
7865                                    + tree.name + " is from package "
7866                                    + tree.sourcePackage);
7867                        }
7868                    } else {
7869                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7870                                + p.info.packageName + " ignored: original from "
7871                                + bp.sourcePackage);
7872                    }
7873                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7874                    if (r == null) {
7875                        r = new StringBuilder(256);
7876                    } else {
7877                        r.append(' ');
7878                    }
7879                    r.append("DUP:");
7880                    r.append(p.info.name);
7881                }
7882                if (bp.perm == p) {
7883                    bp.protectionLevel = p.info.protectionLevel;
7884                }
7885            }
7886
7887            if (r != null) {
7888                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7889            }
7890
7891            N = pkg.instrumentation.size();
7892            r = null;
7893            for (i=0; i<N; i++) {
7894                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7895                a.info.packageName = pkg.applicationInfo.packageName;
7896                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7897                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7898                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7899                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7900                a.info.dataDir = pkg.applicationInfo.dataDir;
7901                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7902                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7903
7904                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7905                // need other information about the application, like the ABI and what not ?
7906                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7907                mInstrumentation.put(a.getComponentName(), a);
7908                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7909                    if (r == null) {
7910                        r = new StringBuilder(256);
7911                    } else {
7912                        r.append(' ');
7913                    }
7914                    r.append(a.info.name);
7915                }
7916            }
7917            if (r != null) {
7918                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7919            }
7920
7921            if (pkg.protectedBroadcasts != null) {
7922                N = pkg.protectedBroadcasts.size();
7923                for (i=0; i<N; i++) {
7924                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7925                }
7926            }
7927
7928            pkgSetting.setTimeStamp(scanFileTime);
7929
7930            // Create idmap files for pairs of (packages, overlay packages).
7931            // Note: "android", ie framework-res.apk, is handled by native layers.
7932            if (pkg.mOverlayTarget != null) {
7933                // This is an overlay package.
7934                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7935                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7936                        mOverlays.put(pkg.mOverlayTarget,
7937                                new ArrayMap<String, PackageParser.Package>());
7938                    }
7939                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7940                    map.put(pkg.packageName, pkg);
7941                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7942                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7943                        createIdmapFailed = true;
7944                    }
7945                }
7946            } else if (mOverlays.containsKey(pkg.packageName) &&
7947                    !pkg.packageName.equals("android")) {
7948                // This is a regular package, with one or more known overlay packages.
7949                createIdmapsForPackageLI(pkg);
7950            }
7951        }
7952
7953        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7954
7955        if (createIdmapFailed) {
7956            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7957                    "scanPackageLI failed to createIdmap");
7958        }
7959        return pkg;
7960    }
7961
7962    /**
7963     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7964     * is derived purely on the basis of the contents of {@code scanFile} and
7965     * {@code cpuAbiOverride}.
7966     *
7967     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7968     */
7969    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7970                                 String cpuAbiOverride, boolean extractLibs)
7971            throws PackageManagerException {
7972        // TODO: We can probably be smarter about this stuff. For installed apps,
7973        // we can calculate this information at install time once and for all. For
7974        // system apps, we can probably assume that this information doesn't change
7975        // after the first boot scan. As things stand, we do lots of unnecessary work.
7976
7977        // Give ourselves some initial paths; we'll come back for another
7978        // pass once we've determined ABI below.
7979        setNativeLibraryPaths(pkg);
7980
7981        // We would never need to extract libs for forward-locked and external packages,
7982        // since the container service will do it for us. We shouldn't attempt to
7983        // extract libs from system app when it was not updated.
7984        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7985                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7986            extractLibs = false;
7987        }
7988
7989        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7990        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7991
7992        NativeLibraryHelper.Handle handle = null;
7993        try {
7994            handle = NativeLibraryHelper.Handle.create(pkg);
7995            // TODO(multiArch): This can be null for apps that didn't go through the
7996            // usual installation process. We can calculate it again, like we
7997            // do during install time.
7998            //
7999            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8000            // unnecessary.
8001            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8002
8003            // Null out the abis so that they can be recalculated.
8004            pkg.applicationInfo.primaryCpuAbi = null;
8005            pkg.applicationInfo.secondaryCpuAbi = null;
8006            if (isMultiArch(pkg.applicationInfo)) {
8007                // Warn if we've set an abiOverride for multi-lib packages..
8008                // By definition, we need to copy both 32 and 64 bit libraries for
8009                // such packages.
8010                if (pkg.cpuAbiOverride != null
8011                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8012                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8013                }
8014
8015                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8016                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8017                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8018                    if (extractLibs) {
8019                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8020                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8021                                useIsaSpecificSubdirs);
8022                    } else {
8023                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8024                    }
8025                }
8026
8027                maybeThrowExceptionForMultiArchCopy(
8028                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8029
8030                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8031                    if (extractLibs) {
8032                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8033                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8034                                useIsaSpecificSubdirs);
8035                    } else {
8036                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8037                    }
8038                }
8039
8040                maybeThrowExceptionForMultiArchCopy(
8041                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8042
8043                if (abi64 >= 0) {
8044                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8045                }
8046
8047                if (abi32 >= 0) {
8048                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8049                    if (abi64 >= 0) {
8050                        pkg.applicationInfo.secondaryCpuAbi = abi;
8051                    } else {
8052                        pkg.applicationInfo.primaryCpuAbi = abi;
8053                    }
8054                }
8055            } else {
8056                String[] abiList = (cpuAbiOverride != null) ?
8057                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8058
8059                // Enable gross and lame hacks for apps that are built with old
8060                // SDK tools. We must scan their APKs for renderscript bitcode and
8061                // not launch them if it's present. Don't bother checking on devices
8062                // that don't have 64 bit support.
8063                boolean needsRenderScriptOverride = false;
8064                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8065                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8066                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8067                    needsRenderScriptOverride = true;
8068                }
8069
8070                final int copyRet;
8071                if (extractLibs) {
8072                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8073                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8074                } else {
8075                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8076                }
8077
8078                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8079                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8080                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8081                }
8082
8083                if (copyRet >= 0) {
8084                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8085                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8086                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8087                } else if (needsRenderScriptOverride) {
8088                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8089                }
8090            }
8091        } catch (IOException ioe) {
8092            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8093        } finally {
8094            IoUtils.closeQuietly(handle);
8095        }
8096
8097        // Now that we've calculated the ABIs and determined if it's an internal app,
8098        // we will go ahead and populate the nativeLibraryPath.
8099        setNativeLibraryPaths(pkg);
8100    }
8101
8102    /**
8103     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8104     * i.e, so that all packages can be run inside a single process if required.
8105     *
8106     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8107     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8108     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8109     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8110     * updating a package that belongs to a shared user.
8111     *
8112     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8113     * adds unnecessary complexity.
8114     */
8115    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8116            PackageParser.Package scannedPackage, boolean bootComplete) {
8117        String requiredInstructionSet = null;
8118        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8119            requiredInstructionSet = VMRuntime.getInstructionSet(
8120                     scannedPackage.applicationInfo.primaryCpuAbi);
8121        }
8122
8123        PackageSetting requirer = null;
8124        for (PackageSetting ps : packagesForUser) {
8125            // If packagesForUser contains scannedPackage, we skip it. This will happen
8126            // when scannedPackage is an update of an existing package. Without this check,
8127            // we will never be able to change the ABI of any package belonging to a shared
8128            // user, even if it's compatible with other packages.
8129            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8130                if (ps.primaryCpuAbiString == null) {
8131                    continue;
8132                }
8133
8134                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8135                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8136                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8137                    // this but there's not much we can do.
8138                    String errorMessage = "Instruction set mismatch, "
8139                            + ((requirer == null) ? "[caller]" : requirer)
8140                            + " requires " + requiredInstructionSet + " whereas " + ps
8141                            + " requires " + instructionSet;
8142                    Slog.w(TAG, errorMessage);
8143                }
8144
8145                if (requiredInstructionSet == null) {
8146                    requiredInstructionSet = instructionSet;
8147                    requirer = ps;
8148                }
8149            }
8150        }
8151
8152        if (requiredInstructionSet != null) {
8153            String adjustedAbi;
8154            if (requirer != null) {
8155                // requirer != null implies that either scannedPackage was null or that scannedPackage
8156                // did not require an ABI, in which case we have to adjust scannedPackage to match
8157                // the ABI of the set (which is the same as requirer's ABI)
8158                adjustedAbi = requirer.primaryCpuAbiString;
8159                if (scannedPackage != null) {
8160                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8161                }
8162            } else {
8163                // requirer == null implies that we're updating all ABIs in the set to
8164                // match scannedPackage.
8165                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8166            }
8167
8168            for (PackageSetting ps : packagesForUser) {
8169                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8170                    if (ps.primaryCpuAbiString != null) {
8171                        continue;
8172                    }
8173
8174                    ps.primaryCpuAbiString = adjustedAbi;
8175                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8176                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8177                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8178                        try {
8179                            mInstaller.rmdex(ps.codePathString,
8180                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8181                        } catch (InstallerException ignored) {
8182                        }
8183                    }
8184                }
8185            }
8186        }
8187    }
8188
8189    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8190        synchronized (mPackages) {
8191            mResolverReplaced = true;
8192            // Set up information for custom user intent resolution activity.
8193            mResolveActivity.applicationInfo = pkg.applicationInfo;
8194            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8195            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8196            mResolveActivity.processName = pkg.applicationInfo.packageName;
8197            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8198            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8199                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8200            mResolveActivity.theme = 0;
8201            mResolveActivity.exported = true;
8202            mResolveActivity.enabled = true;
8203            mResolveInfo.activityInfo = mResolveActivity;
8204            mResolveInfo.priority = 0;
8205            mResolveInfo.preferredOrder = 0;
8206            mResolveInfo.match = 0;
8207            mResolveComponentName = mCustomResolverComponentName;
8208            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8209                    mResolveComponentName);
8210        }
8211    }
8212
8213    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8214        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8215
8216        // Set up information for ephemeral installer activity
8217        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8218        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8219        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8220        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8221        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8222        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8223                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8224        mEphemeralInstallerActivity.theme = 0;
8225        mEphemeralInstallerActivity.exported = true;
8226        mEphemeralInstallerActivity.enabled = true;
8227        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8228        mEphemeralInstallerInfo.priority = 0;
8229        mEphemeralInstallerInfo.preferredOrder = 0;
8230        mEphemeralInstallerInfo.match = 0;
8231
8232        if (DEBUG_EPHEMERAL) {
8233            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8234        }
8235    }
8236
8237    private static String calculateBundledApkRoot(final String codePathString) {
8238        final File codePath = new File(codePathString);
8239        final File codeRoot;
8240        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8241            codeRoot = Environment.getRootDirectory();
8242        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8243            codeRoot = Environment.getOemDirectory();
8244        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8245            codeRoot = Environment.getVendorDirectory();
8246        } else {
8247            // Unrecognized code path; take its top real segment as the apk root:
8248            // e.g. /something/app/blah.apk => /something
8249            try {
8250                File f = codePath.getCanonicalFile();
8251                File parent = f.getParentFile();    // non-null because codePath is a file
8252                File tmp;
8253                while ((tmp = parent.getParentFile()) != null) {
8254                    f = parent;
8255                    parent = tmp;
8256                }
8257                codeRoot = f;
8258                Slog.w(TAG, "Unrecognized code path "
8259                        + codePath + " - using " + codeRoot);
8260            } catch (IOException e) {
8261                // Can't canonicalize the code path -- shenanigans?
8262                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8263                return Environment.getRootDirectory().getPath();
8264            }
8265        }
8266        return codeRoot.getPath();
8267    }
8268
8269    /**
8270     * Derive and set the location of native libraries for the given package,
8271     * which varies depending on where and how the package was installed.
8272     */
8273    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8274        final ApplicationInfo info = pkg.applicationInfo;
8275        final String codePath = pkg.codePath;
8276        final File codeFile = new File(codePath);
8277        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8278        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8279
8280        info.nativeLibraryRootDir = null;
8281        info.nativeLibraryRootRequiresIsa = false;
8282        info.nativeLibraryDir = null;
8283        info.secondaryNativeLibraryDir = null;
8284
8285        if (isApkFile(codeFile)) {
8286            // Monolithic install
8287            if (bundledApp) {
8288                // If "/system/lib64/apkname" exists, assume that is the per-package
8289                // native library directory to use; otherwise use "/system/lib/apkname".
8290                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8291                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8292                        getPrimaryInstructionSet(info));
8293
8294                // This is a bundled system app so choose the path based on the ABI.
8295                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8296                // is just the default path.
8297                final String apkName = deriveCodePathName(codePath);
8298                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8299                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8300                        apkName).getAbsolutePath();
8301
8302                if (info.secondaryCpuAbi != null) {
8303                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8304                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8305                            secondaryLibDir, apkName).getAbsolutePath();
8306                }
8307            } else if (asecApp) {
8308                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8309                        .getAbsolutePath();
8310            } else {
8311                final String apkName = deriveCodePathName(codePath);
8312                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8313                        .getAbsolutePath();
8314            }
8315
8316            info.nativeLibraryRootRequiresIsa = false;
8317            info.nativeLibraryDir = info.nativeLibraryRootDir;
8318        } else {
8319            // Cluster install
8320            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8321            info.nativeLibraryRootRequiresIsa = true;
8322
8323            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8324                    getPrimaryInstructionSet(info)).getAbsolutePath();
8325
8326            if (info.secondaryCpuAbi != null) {
8327                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8328                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8329            }
8330        }
8331    }
8332
8333    /**
8334     * Calculate the abis and roots for a bundled app. These can uniquely
8335     * be determined from the contents of the system partition, i.e whether
8336     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8337     * of this information, and instead assume that the system was built
8338     * sensibly.
8339     */
8340    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8341                                           PackageSetting pkgSetting) {
8342        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8343
8344        // If "/system/lib64/apkname" exists, assume that is the per-package
8345        // native library directory to use; otherwise use "/system/lib/apkname".
8346        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8347        setBundledAppAbi(pkg, apkRoot, apkName);
8348        // pkgSetting might be null during rescan following uninstall of updates
8349        // to a bundled app, so accommodate that possibility.  The settings in
8350        // that case will be established later from the parsed package.
8351        //
8352        // If the settings aren't null, sync them up with what we've just derived.
8353        // note that apkRoot isn't stored in the package settings.
8354        if (pkgSetting != null) {
8355            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8356            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8357        }
8358    }
8359
8360    /**
8361     * Deduces the ABI of a bundled app and sets the relevant fields on the
8362     * parsed pkg object.
8363     *
8364     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8365     *        under which system libraries are installed.
8366     * @param apkName the name of the installed package.
8367     */
8368    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8369        final File codeFile = new File(pkg.codePath);
8370
8371        final boolean has64BitLibs;
8372        final boolean has32BitLibs;
8373        if (isApkFile(codeFile)) {
8374            // Monolithic install
8375            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8376            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8377        } else {
8378            // Cluster install
8379            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8380            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8381                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8382                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8383                has64BitLibs = (new File(rootDir, isa)).exists();
8384            } else {
8385                has64BitLibs = false;
8386            }
8387            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8388                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8389                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8390                has32BitLibs = (new File(rootDir, isa)).exists();
8391            } else {
8392                has32BitLibs = false;
8393            }
8394        }
8395
8396        if (has64BitLibs && !has32BitLibs) {
8397            // The package has 64 bit libs, but not 32 bit libs. Its primary
8398            // ABI should be 64 bit. We can safely assume here that the bundled
8399            // native libraries correspond to the most preferred ABI in the list.
8400
8401            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8402            pkg.applicationInfo.secondaryCpuAbi = null;
8403        } else if (has32BitLibs && !has64BitLibs) {
8404            // The package has 32 bit libs but not 64 bit libs. Its primary
8405            // ABI should be 32 bit.
8406
8407            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8408            pkg.applicationInfo.secondaryCpuAbi = null;
8409        } else if (has32BitLibs && has64BitLibs) {
8410            // The application has both 64 and 32 bit bundled libraries. We check
8411            // here that the app declares multiArch support, and warn if it doesn't.
8412            //
8413            // We will be lenient here and record both ABIs. The primary will be the
8414            // ABI that's higher on the list, i.e, a device that's configured to prefer
8415            // 64 bit apps will see a 64 bit primary ABI,
8416
8417            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8418                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8419            }
8420
8421            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8422                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8423                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8424            } else {
8425                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8426                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8427            }
8428        } else {
8429            pkg.applicationInfo.primaryCpuAbi = null;
8430            pkg.applicationInfo.secondaryCpuAbi = null;
8431        }
8432    }
8433
8434    private void killApplication(String pkgName, int appId, String reason) {
8435        // Request the ActivityManager to kill the process(only for existing packages)
8436        // so that we do not end up in a confused state while the user is still using the older
8437        // version of the application while the new one gets installed.
8438        IActivityManager am = ActivityManagerNative.getDefault();
8439        if (am != null) {
8440            try {
8441                am.killApplicationWithAppId(pkgName, appId, reason);
8442            } catch (RemoteException e) {
8443            }
8444        }
8445    }
8446
8447    void removePackageLI(PackageSetting ps, boolean chatty) {
8448        if (DEBUG_INSTALL) {
8449            if (chatty)
8450                Log.d(TAG, "Removing package " + ps.name);
8451        }
8452
8453        // writer
8454        synchronized (mPackages) {
8455            mPackages.remove(ps.name);
8456            final PackageParser.Package pkg = ps.pkg;
8457            if (pkg != null) {
8458                cleanPackageDataStructuresLILPw(pkg, chatty);
8459            }
8460        }
8461    }
8462
8463    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8464        if (DEBUG_INSTALL) {
8465            if (chatty)
8466                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8467        }
8468
8469        // writer
8470        synchronized (mPackages) {
8471            mPackages.remove(pkg.applicationInfo.packageName);
8472            cleanPackageDataStructuresLILPw(pkg, chatty);
8473        }
8474    }
8475
8476    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8477        int N = pkg.providers.size();
8478        StringBuilder r = null;
8479        int i;
8480        for (i=0; i<N; i++) {
8481            PackageParser.Provider p = pkg.providers.get(i);
8482            mProviders.removeProvider(p);
8483            if (p.info.authority == null) {
8484
8485                /* There was another ContentProvider with this authority when
8486                 * this app was installed so this authority is null,
8487                 * Ignore it as we don't have to unregister the provider.
8488                 */
8489                continue;
8490            }
8491            String names[] = p.info.authority.split(";");
8492            for (int j = 0; j < names.length; j++) {
8493                if (mProvidersByAuthority.get(names[j]) == p) {
8494                    mProvidersByAuthority.remove(names[j]);
8495                    if (DEBUG_REMOVE) {
8496                        if (chatty)
8497                            Log.d(TAG, "Unregistered content provider: " + names[j]
8498                                    + ", className = " + p.info.name + ", isSyncable = "
8499                                    + p.info.isSyncable);
8500                    }
8501                }
8502            }
8503            if (DEBUG_REMOVE && chatty) {
8504                if (r == null) {
8505                    r = new StringBuilder(256);
8506                } else {
8507                    r.append(' ');
8508                }
8509                r.append(p.info.name);
8510            }
8511        }
8512        if (r != null) {
8513            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8514        }
8515
8516        N = pkg.services.size();
8517        r = null;
8518        for (i=0; i<N; i++) {
8519            PackageParser.Service s = pkg.services.get(i);
8520            mServices.removeService(s);
8521            if (chatty) {
8522                if (r == null) {
8523                    r = new StringBuilder(256);
8524                } else {
8525                    r.append(' ');
8526                }
8527                r.append(s.info.name);
8528            }
8529        }
8530        if (r != null) {
8531            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8532        }
8533
8534        N = pkg.receivers.size();
8535        r = null;
8536        for (i=0; i<N; i++) {
8537            PackageParser.Activity a = pkg.receivers.get(i);
8538            mReceivers.removeActivity(a, "receiver");
8539            if (DEBUG_REMOVE && chatty) {
8540                if (r == null) {
8541                    r = new StringBuilder(256);
8542                } else {
8543                    r.append(' ');
8544                }
8545                r.append(a.info.name);
8546            }
8547        }
8548        if (r != null) {
8549            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8550        }
8551
8552        N = pkg.activities.size();
8553        r = null;
8554        for (i=0; i<N; i++) {
8555            PackageParser.Activity a = pkg.activities.get(i);
8556            mActivities.removeActivity(a, "activity");
8557            if (DEBUG_REMOVE && chatty) {
8558                if (r == null) {
8559                    r = new StringBuilder(256);
8560                } else {
8561                    r.append(' ');
8562                }
8563                r.append(a.info.name);
8564            }
8565        }
8566        if (r != null) {
8567            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8568        }
8569
8570        N = pkg.permissions.size();
8571        r = null;
8572        for (i=0; i<N; i++) {
8573            PackageParser.Permission p = pkg.permissions.get(i);
8574            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8575            if (bp == null) {
8576                bp = mSettings.mPermissionTrees.get(p.info.name);
8577            }
8578            if (bp != null && bp.perm == p) {
8579                bp.perm = null;
8580                if (DEBUG_REMOVE && chatty) {
8581                    if (r == null) {
8582                        r = new StringBuilder(256);
8583                    } else {
8584                        r.append(' ');
8585                    }
8586                    r.append(p.info.name);
8587                }
8588            }
8589            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8590                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8591                if (appOpPkgs != null) {
8592                    appOpPkgs.remove(pkg.packageName);
8593                }
8594            }
8595        }
8596        if (r != null) {
8597            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8598        }
8599
8600        N = pkg.requestedPermissions.size();
8601        r = null;
8602        for (i=0; i<N; i++) {
8603            String perm = pkg.requestedPermissions.get(i);
8604            BasePermission bp = mSettings.mPermissions.get(perm);
8605            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8606                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8607                if (appOpPkgs != null) {
8608                    appOpPkgs.remove(pkg.packageName);
8609                    if (appOpPkgs.isEmpty()) {
8610                        mAppOpPermissionPackages.remove(perm);
8611                    }
8612                }
8613            }
8614        }
8615        if (r != null) {
8616            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8617        }
8618
8619        N = pkg.instrumentation.size();
8620        r = null;
8621        for (i=0; i<N; i++) {
8622            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8623            mInstrumentation.remove(a.getComponentName());
8624            if (DEBUG_REMOVE && chatty) {
8625                if (r == null) {
8626                    r = new StringBuilder(256);
8627                } else {
8628                    r.append(' ');
8629                }
8630                r.append(a.info.name);
8631            }
8632        }
8633        if (r != null) {
8634            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8635        }
8636
8637        r = null;
8638        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8639            // Only system apps can hold shared libraries.
8640            if (pkg.libraryNames != null) {
8641                for (i=0; i<pkg.libraryNames.size(); i++) {
8642                    String name = pkg.libraryNames.get(i);
8643                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8644                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8645                        mSharedLibraries.remove(name);
8646                        if (DEBUG_REMOVE && chatty) {
8647                            if (r == null) {
8648                                r = new StringBuilder(256);
8649                            } else {
8650                                r.append(' ');
8651                            }
8652                            r.append(name);
8653                        }
8654                    }
8655                }
8656            }
8657        }
8658        if (r != null) {
8659            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8660        }
8661    }
8662
8663    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8664        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8665            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8666                return true;
8667            }
8668        }
8669        return false;
8670    }
8671
8672    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8673    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8674    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8675
8676    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8677            int flags) {
8678        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8679        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8680    }
8681
8682    private void updatePermissionsLPw(String changingPkg,
8683            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8684        // Make sure there are no dangling permission trees.
8685        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8686        while (it.hasNext()) {
8687            final BasePermission bp = it.next();
8688            if (bp.packageSetting == null) {
8689                // We may not yet have parsed the package, so just see if
8690                // we still know about its settings.
8691                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8692            }
8693            if (bp.packageSetting == null) {
8694                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8695                        + " from package " + bp.sourcePackage);
8696                it.remove();
8697            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8698                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8699                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8700                            + " from package " + bp.sourcePackage);
8701                    flags |= UPDATE_PERMISSIONS_ALL;
8702                    it.remove();
8703                }
8704            }
8705        }
8706
8707        // Make sure all dynamic permissions have been assigned to a package,
8708        // and make sure there are no dangling permissions.
8709        it = mSettings.mPermissions.values().iterator();
8710        while (it.hasNext()) {
8711            final BasePermission bp = it.next();
8712            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8713                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8714                        + bp.name + " pkg=" + bp.sourcePackage
8715                        + " info=" + bp.pendingInfo);
8716                if (bp.packageSetting == null && bp.pendingInfo != null) {
8717                    final BasePermission tree = findPermissionTreeLP(bp.name);
8718                    if (tree != null && tree.perm != null) {
8719                        bp.packageSetting = tree.packageSetting;
8720                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8721                                new PermissionInfo(bp.pendingInfo));
8722                        bp.perm.info.packageName = tree.perm.info.packageName;
8723                        bp.perm.info.name = bp.name;
8724                        bp.uid = tree.uid;
8725                    }
8726                }
8727            }
8728            if (bp.packageSetting == null) {
8729                // We may not yet have parsed the package, so just see if
8730                // we still know about its settings.
8731                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8732            }
8733            if (bp.packageSetting == null) {
8734                Slog.w(TAG, "Removing dangling permission: " + bp.name
8735                        + " from package " + bp.sourcePackage);
8736                it.remove();
8737            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8738                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8739                    Slog.i(TAG, "Removing old permission: " + bp.name
8740                            + " from package " + bp.sourcePackage);
8741                    flags |= UPDATE_PERMISSIONS_ALL;
8742                    it.remove();
8743                }
8744            }
8745        }
8746
8747        // Now update the permissions for all packages, in particular
8748        // replace the granted permissions of the system packages.
8749        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8750            for (PackageParser.Package pkg : mPackages.values()) {
8751                if (pkg != pkgInfo) {
8752                    // Only replace for packages on requested volume
8753                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8754                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8755                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8756                    grantPermissionsLPw(pkg, replace, changingPkg);
8757                }
8758            }
8759        }
8760
8761        if (pkgInfo != null) {
8762            // Only replace for packages on requested volume
8763            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8764            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8765                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8766            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8767        }
8768    }
8769
8770    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8771            String packageOfInterest) {
8772        // IMPORTANT: There are two types of permissions: install and runtime.
8773        // Install time permissions are granted when the app is installed to
8774        // all device users and users added in the future. Runtime permissions
8775        // are granted at runtime explicitly to specific users. Normal and signature
8776        // protected permissions are install time permissions. Dangerous permissions
8777        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8778        // otherwise they are runtime permissions. This function does not manage
8779        // runtime permissions except for the case an app targeting Lollipop MR1
8780        // being upgraded to target a newer SDK, in which case dangerous permissions
8781        // are transformed from install time to runtime ones.
8782
8783        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8784        if (ps == null) {
8785            return;
8786        }
8787
8788        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8789
8790        PermissionsState permissionsState = ps.getPermissionsState();
8791        PermissionsState origPermissions = permissionsState;
8792
8793        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8794
8795        boolean runtimePermissionsRevoked = false;
8796        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8797
8798        boolean changedInstallPermission = false;
8799
8800        if (replace) {
8801            ps.installPermissionsFixed = false;
8802            if (!ps.isSharedUser()) {
8803                origPermissions = new PermissionsState(permissionsState);
8804                permissionsState.reset();
8805            } else {
8806                // We need to know only about runtime permission changes since the
8807                // calling code always writes the install permissions state but
8808                // the runtime ones are written only if changed. The only cases of
8809                // changed runtime permissions here are promotion of an install to
8810                // runtime and revocation of a runtime from a shared user.
8811                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8812                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8813                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8814                    runtimePermissionsRevoked = true;
8815                }
8816            }
8817        }
8818
8819        permissionsState.setGlobalGids(mGlobalGids);
8820
8821        final int N = pkg.requestedPermissions.size();
8822        for (int i=0; i<N; i++) {
8823            final String name = pkg.requestedPermissions.get(i);
8824            final BasePermission bp = mSettings.mPermissions.get(name);
8825
8826            if (DEBUG_INSTALL) {
8827                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8828            }
8829
8830            if (bp == null || bp.packageSetting == null) {
8831                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8832                    Slog.w(TAG, "Unknown permission " + name
8833                            + " in package " + pkg.packageName);
8834                }
8835                continue;
8836            }
8837
8838            final String perm = bp.name;
8839            boolean allowedSig = false;
8840            int grant = GRANT_DENIED;
8841
8842            // Keep track of app op permissions.
8843            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8844                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8845                if (pkgs == null) {
8846                    pkgs = new ArraySet<>();
8847                    mAppOpPermissionPackages.put(bp.name, pkgs);
8848                }
8849                pkgs.add(pkg.packageName);
8850            }
8851
8852            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8853            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8854                    >= Build.VERSION_CODES.M;
8855            switch (level) {
8856                case PermissionInfo.PROTECTION_NORMAL: {
8857                    // For all apps normal permissions are install time ones.
8858                    grant = GRANT_INSTALL;
8859                } break;
8860
8861                case PermissionInfo.PROTECTION_DANGEROUS: {
8862                    // If a permission review is required for legacy apps we represent
8863                    // their permissions as always granted runtime ones since we need
8864                    // to keep the review required permission flag per user while an
8865                    // install permission's state is shared across all users.
8866                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8867                        // For legacy apps dangerous permissions are install time ones.
8868                        grant = GRANT_INSTALL;
8869                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8870                        // For legacy apps that became modern, install becomes runtime.
8871                        grant = GRANT_UPGRADE;
8872                    } else if (mPromoteSystemApps
8873                            && isSystemApp(ps)
8874                            && mExistingSystemPackages.contains(ps.name)) {
8875                        // For legacy system apps, install becomes runtime.
8876                        // We cannot check hasInstallPermission() for system apps since those
8877                        // permissions were granted implicitly and not persisted pre-M.
8878                        grant = GRANT_UPGRADE;
8879                    } else {
8880                        // For modern apps keep runtime permissions unchanged.
8881                        grant = GRANT_RUNTIME;
8882                    }
8883                } break;
8884
8885                case PermissionInfo.PROTECTION_SIGNATURE: {
8886                    // For all apps signature permissions are install time ones.
8887                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8888                    if (allowedSig) {
8889                        grant = GRANT_INSTALL;
8890                    }
8891                } break;
8892            }
8893
8894            if (DEBUG_INSTALL) {
8895                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8896            }
8897
8898            if (grant != GRANT_DENIED) {
8899                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8900                    // If this is an existing, non-system package, then
8901                    // we can't add any new permissions to it.
8902                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8903                        // Except...  if this is a permission that was added
8904                        // to the platform (note: need to only do this when
8905                        // updating the platform).
8906                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8907                            grant = GRANT_DENIED;
8908                        }
8909                    }
8910                }
8911
8912                switch (grant) {
8913                    case GRANT_INSTALL: {
8914                        // Revoke this as runtime permission to handle the case of
8915                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8916                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8917                            if (origPermissions.getRuntimePermissionState(
8918                                    bp.name, userId) != null) {
8919                                // Revoke the runtime permission and clear the flags.
8920                                origPermissions.revokeRuntimePermission(bp, userId);
8921                                origPermissions.updatePermissionFlags(bp, userId,
8922                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8923                                // If we revoked a permission permission, we have to write.
8924                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8925                                        changedRuntimePermissionUserIds, userId);
8926                            }
8927                        }
8928                        // Grant an install permission.
8929                        if (permissionsState.grantInstallPermission(bp) !=
8930                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8931                            changedInstallPermission = true;
8932                        }
8933                    } break;
8934
8935                    case GRANT_RUNTIME: {
8936                        // Grant previously granted runtime permissions.
8937                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8938                            PermissionState permissionState = origPermissions
8939                                    .getRuntimePermissionState(bp.name, userId);
8940                            int flags = permissionState != null
8941                                    ? permissionState.getFlags() : 0;
8942                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8943                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8944                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8945                                    // If we cannot put the permission as it was, we have to write.
8946                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8947                                            changedRuntimePermissionUserIds, userId);
8948                                }
8949                                // If the app supports runtime permissions no need for a review.
8950                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8951                                        && appSupportsRuntimePermissions
8952                                        && (flags & PackageManager
8953                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8954                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8955                                    // Since we changed the flags, we have to write.
8956                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8957                                            changedRuntimePermissionUserIds, userId);
8958                                }
8959                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8960                                    && !appSupportsRuntimePermissions) {
8961                                // For legacy apps that need a permission review, every new
8962                                // runtime permission is granted but it is pending a review.
8963                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8964                                    permissionsState.grantRuntimePermission(bp, userId);
8965                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8966                                    // We changed the permission and flags, hence have to write.
8967                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8968                                            changedRuntimePermissionUserIds, userId);
8969                                }
8970                            }
8971                            // Propagate the permission flags.
8972                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8973                        }
8974                    } break;
8975
8976                    case GRANT_UPGRADE: {
8977                        // Grant runtime permissions for a previously held install permission.
8978                        PermissionState permissionState = origPermissions
8979                                .getInstallPermissionState(bp.name);
8980                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8981
8982                        if (origPermissions.revokeInstallPermission(bp)
8983                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8984                            // We will be transferring the permission flags, so clear them.
8985                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8986                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8987                            changedInstallPermission = true;
8988                        }
8989
8990                        // If the permission is not to be promoted to runtime we ignore it and
8991                        // also its other flags as they are not applicable to install permissions.
8992                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8993                            for (int userId : currentUserIds) {
8994                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8995                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8996                                    // Transfer the permission flags.
8997                                    permissionsState.updatePermissionFlags(bp, userId,
8998                                            flags, flags);
8999                                    // If we granted the permission, we have to write.
9000                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9001                                            changedRuntimePermissionUserIds, userId);
9002                                }
9003                            }
9004                        }
9005                    } break;
9006
9007                    default: {
9008                        if (packageOfInterest == null
9009                                || packageOfInterest.equals(pkg.packageName)) {
9010                            Slog.w(TAG, "Not granting permission " + perm
9011                                    + " to package " + pkg.packageName
9012                                    + " because it was previously installed without");
9013                        }
9014                    } break;
9015                }
9016            } else {
9017                if (permissionsState.revokeInstallPermission(bp) !=
9018                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9019                    // Also drop the permission flags.
9020                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9021                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9022                    changedInstallPermission = true;
9023                    Slog.i(TAG, "Un-granting permission " + perm
9024                            + " from package " + pkg.packageName
9025                            + " (protectionLevel=" + bp.protectionLevel
9026                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9027                            + ")");
9028                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9029                    // Don't print warning for app op permissions, since it is fine for them
9030                    // not to be granted, there is a UI for the user to decide.
9031                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9032                        Slog.w(TAG, "Not granting permission " + perm
9033                                + " to package " + pkg.packageName
9034                                + " (protectionLevel=" + bp.protectionLevel
9035                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9036                                + ")");
9037                    }
9038                }
9039            }
9040        }
9041
9042        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9043                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9044            // This is the first that we have heard about this package, so the
9045            // permissions we have now selected are fixed until explicitly
9046            // changed.
9047            ps.installPermissionsFixed = true;
9048        }
9049
9050        // Persist the runtime permissions state for users with changes. If permissions
9051        // were revoked because no app in the shared user declares them we have to
9052        // write synchronously to avoid losing runtime permissions state.
9053        for (int userId : changedRuntimePermissionUserIds) {
9054            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9055        }
9056
9057        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9058    }
9059
9060    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9061        boolean allowed = false;
9062        final int NP = PackageParser.NEW_PERMISSIONS.length;
9063        for (int ip=0; ip<NP; ip++) {
9064            final PackageParser.NewPermissionInfo npi
9065                    = PackageParser.NEW_PERMISSIONS[ip];
9066            if (npi.name.equals(perm)
9067                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9068                allowed = true;
9069                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9070                        + pkg.packageName);
9071                break;
9072            }
9073        }
9074        return allowed;
9075    }
9076
9077    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9078            BasePermission bp, PermissionsState origPermissions) {
9079        boolean allowed;
9080        allowed = (compareSignatures(
9081                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9082                        == PackageManager.SIGNATURE_MATCH)
9083                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9084                        == PackageManager.SIGNATURE_MATCH);
9085        if (!allowed && (bp.protectionLevel
9086                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9087            if (isSystemApp(pkg)) {
9088                // For updated system applications, a system permission
9089                // is granted only if it had been defined by the original application.
9090                if (pkg.isUpdatedSystemApp()) {
9091                    final PackageSetting sysPs = mSettings
9092                            .getDisabledSystemPkgLPr(pkg.packageName);
9093                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9094                        // If the original was granted this permission, we take
9095                        // that grant decision as read and propagate it to the
9096                        // update.
9097                        if (sysPs.isPrivileged()) {
9098                            allowed = true;
9099                        }
9100                    } else {
9101                        // The system apk may have been updated with an older
9102                        // version of the one on the data partition, but which
9103                        // granted a new system permission that it didn't have
9104                        // before.  In this case we do want to allow the app to
9105                        // now get the new permission if the ancestral apk is
9106                        // privileged to get it.
9107                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9108                            for (int j=0;
9109                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9110                                if (perm.equals(
9111                                        sysPs.pkg.requestedPermissions.get(j))) {
9112                                    allowed = true;
9113                                    break;
9114                                }
9115                            }
9116                        }
9117                    }
9118                } else {
9119                    allowed = isPrivilegedApp(pkg);
9120                }
9121            }
9122        }
9123        if (!allowed) {
9124            if (!allowed && (bp.protectionLevel
9125                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9126                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9127                // If this was a previously normal/dangerous permission that got moved
9128                // to a system permission as part of the runtime permission redesign, then
9129                // we still want to blindly grant it to old apps.
9130                allowed = true;
9131            }
9132            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9133                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9134                // If this permission is to be granted to the system installer and
9135                // this app is an installer, then it gets the permission.
9136                allowed = true;
9137            }
9138            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9139                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9140                // If this permission is to be granted to the system verifier and
9141                // this app is a verifier, then it gets the permission.
9142                allowed = true;
9143            }
9144            if (!allowed && (bp.protectionLevel
9145                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9146                    && isSystemApp(pkg)) {
9147                // Any pre-installed system app is allowed to get this permission.
9148                allowed = true;
9149            }
9150            if (!allowed && (bp.protectionLevel
9151                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9152                // For development permissions, a development permission
9153                // is granted only if it was already granted.
9154                allowed = origPermissions.hasInstallPermission(perm);
9155            }
9156        }
9157        return allowed;
9158    }
9159
9160    final class ActivityIntentResolver
9161            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9162        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9163                boolean defaultOnly, int userId) {
9164            if (!sUserManager.exists(userId)) return null;
9165            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9166            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9167        }
9168
9169        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9170                int userId) {
9171            if (!sUserManager.exists(userId)) return null;
9172            mFlags = flags;
9173            return super.queryIntent(intent, resolvedType,
9174                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9175        }
9176
9177        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9178                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9179            if (!sUserManager.exists(userId)) return null;
9180            if (packageActivities == null) {
9181                return null;
9182            }
9183            mFlags = flags;
9184            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9185            final int N = packageActivities.size();
9186            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9187                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9188
9189            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9190            for (int i = 0; i < N; ++i) {
9191                intentFilters = packageActivities.get(i).intents;
9192                if (intentFilters != null && intentFilters.size() > 0) {
9193                    PackageParser.ActivityIntentInfo[] array =
9194                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9195                    intentFilters.toArray(array);
9196                    listCut.add(array);
9197                }
9198            }
9199            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9200        }
9201
9202        public final void addActivity(PackageParser.Activity a, String type) {
9203            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9204            mActivities.put(a.getComponentName(), a);
9205            if (DEBUG_SHOW_INFO)
9206                Log.v(
9207                TAG, "  " + type + " " +
9208                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9209            if (DEBUG_SHOW_INFO)
9210                Log.v(TAG, "    Class=" + a.info.name);
9211            final int NI = a.intents.size();
9212            for (int j=0; j<NI; j++) {
9213                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9214                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9215                    intent.setPriority(0);
9216                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9217                            + a.className + " with priority > 0, forcing to 0");
9218                }
9219                if (DEBUG_SHOW_INFO) {
9220                    Log.v(TAG, "    IntentFilter:");
9221                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9222                }
9223                if (!intent.debugCheck()) {
9224                    Log.w(TAG, "==> For Activity " + a.info.name);
9225                }
9226                addFilter(intent);
9227            }
9228        }
9229
9230        public final void removeActivity(PackageParser.Activity a, String type) {
9231            mActivities.remove(a.getComponentName());
9232            if (DEBUG_SHOW_INFO) {
9233                Log.v(TAG, "  " + type + " "
9234                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9235                                : a.info.name) + ":");
9236                Log.v(TAG, "    Class=" + a.info.name);
9237            }
9238            final int NI = a.intents.size();
9239            for (int j=0; j<NI; j++) {
9240                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9241                if (DEBUG_SHOW_INFO) {
9242                    Log.v(TAG, "    IntentFilter:");
9243                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9244                }
9245                removeFilter(intent);
9246            }
9247        }
9248
9249        @Override
9250        protected boolean allowFilterResult(
9251                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9252            ActivityInfo filterAi = filter.activity.info;
9253            for (int i=dest.size()-1; i>=0; i--) {
9254                ActivityInfo destAi = dest.get(i).activityInfo;
9255                if (destAi.name == filterAi.name
9256                        && destAi.packageName == filterAi.packageName) {
9257                    return false;
9258                }
9259            }
9260            return true;
9261        }
9262
9263        @Override
9264        protected ActivityIntentInfo[] newArray(int size) {
9265            return new ActivityIntentInfo[size];
9266        }
9267
9268        @Override
9269        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9270            if (!sUserManager.exists(userId)) return true;
9271            PackageParser.Package p = filter.activity.owner;
9272            if (p != null) {
9273                PackageSetting ps = (PackageSetting)p.mExtras;
9274                if (ps != null) {
9275                    // System apps are never considered stopped for purposes of
9276                    // filtering, because there may be no way for the user to
9277                    // actually re-launch them.
9278                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9279                            && ps.getStopped(userId);
9280                }
9281            }
9282            return false;
9283        }
9284
9285        @Override
9286        protected boolean isPackageForFilter(String packageName,
9287                PackageParser.ActivityIntentInfo info) {
9288            return packageName.equals(info.activity.owner.packageName);
9289        }
9290
9291        @Override
9292        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9293                int match, int userId) {
9294            if (!sUserManager.exists(userId)) return null;
9295            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9296                return null;
9297            }
9298            final PackageParser.Activity activity = info.activity;
9299            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9300            if (ps == null) {
9301                return null;
9302            }
9303            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9304                    ps.readUserState(userId), userId);
9305            if (ai == null) {
9306                return null;
9307            }
9308            final ResolveInfo res = new ResolveInfo();
9309            res.activityInfo = ai;
9310            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9311                res.filter = info;
9312            }
9313            if (info != null) {
9314                res.handleAllWebDataURI = info.handleAllWebDataURI();
9315            }
9316            res.priority = info.getPriority();
9317            res.preferredOrder = activity.owner.mPreferredOrder;
9318            //System.out.println("Result: " + res.activityInfo.className +
9319            //                   " = " + res.priority);
9320            res.match = match;
9321            res.isDefault = info.hasDefault;
9322            res.labelRes = info.labelRes;
9323            res.nonLocalizedLabel = info.nonLocalizedLabel;
9324            if (userNeedsBadging(userId)) {
9325                res.noResourceId = true;
9326            } else {
9327                res.icon = info.icon;
9328            }
9329            res.iconResourceId = info.icon;
9330            res.system = res.activityInfo.applicationInfo.isSystemApp();
9331            return res;
9332        }
9333
9334        @Override
9335        protected void sortResults(List<ResolveInfo> results) {
9336            Collections.sort(results, mResolvePrioritySorter);
9337        }
9338
9339        @Override
9340        protected void dumpFilter(PrintWriter out, String prefix,
9341                PackageParser.ActivityIntentInfo filter) {
9342            out.print(prefix); out.print(
9343                    Integer.toHexString(System.identityHashCode(filter.activity)));
9344                    out.print(' ');
9345                    filter.activity.printComponentShortName(out);
9346                    out.print(" filter ");
9347                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9348        }
9349
9350        @Override
9351        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9352            return filter.activity;
9353        }
9354
9355        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9356            PackageParser.Activity activity = (PackageParser.Activity)label;
9357            out.print(prefix); out.print(
9358                    Integer.toHexString(System.identityHashCode(activity)));
9359                    out.print(' ');
9360                    activity.printComponentShortName(out);
9361            if (count > 1) {
9362                out.print(" ("); out.print(count); out.print(" filters)");
9363            }
9364            out.println();
9365        }
9366
9367//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9368//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9369//            final List<ResolveInfo> retList = Lists.newArrayList();
9370//            while (i.hasNext()) {
9371//                final ResolveInfo resolveInfo = i.next();
9372//                if (isEnabledLP(resolveInfo.activityInfo)) {
9373//                    retList.add(resolveInfo);
9374//                }
9375//            }
9376//            return retList;
9377//        }
9378
9379        // Keys are String (activity class name), values are Activity.
9380        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9381                = new ArrayMap<ComponentName, PackageParser.Activity>();
9382        private int mFlags;
9383    }
9384
9385    private final class ServiceIntentResolver
9386            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9387        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9388                boolean defaultOnly, int userId) {
9389            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9390            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9391        }
9392
9393        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9394                int userId) {
9395            if (!sUserManager.exists(userId)) return null;
9396            mFlags = flags;
9397            return super.queryIntent(intent, resolvedType,
9398                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9399        }
9400
9401        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9402                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9403            if (!sUserManager.exists(userId)) return null;
9404            if (packageServices == null) {
9405                return null;
9406            }
9407            mFlags = flags;
9408            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9409            final int N = packageServices.size();
9410            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9411                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9412
9413            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9414            for (int i = 0; i < N; ++i) {
9415                intentFilters = packageServices.get(i).intents;
9416                if (intentFilters != null && intentFilters.size() > 0) {
9417                    PackageParser.ServiceIntentInfo[] array =
9418                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9419                    intentFilters.toArray(array);
9420                    listCut.add(array);
9421                }
9422            }
9423            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9424        }
9425
9426        public final void addService(PackageParser.Service s) {
9427            mServices.put(s.getComponentName(), s);
9428            if (DEBUG_SHOW_INFO) {
9429                Log.v(TAG, "  "
9430                        + (s.info.nonLocalizedLabel != null
9431                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9432                Log.v(TAG, "    Class=" + s.info.name);
9433            }
9434            final int NI = s.intents.size();
9435            int j;
9436            for (j=0; j<NI; j++) {
9437                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9438                if (DEBUG_SHOW_INFO) {
9439                    Log.v(TAG, "    IntentFilter:");
9440                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9441                }
9442                if (!intent.debugCheck()) {
9443                    Log.w(TAG, "==> For Service " + s.info.name);
9444                }
9445                addFilter(intent);
9446            }
9447        }
9448
9449        public final void removeService(PackageParser.Service s) {
9450            mServices.remove(s.getComponentName());
9451            if (DEBUG_SHOW_INFO) {
9452                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9453                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9454                Log.v(TAG, "    Class=" + s.info.name);
9455            }
9456            final int NI = s.intents.size();
9457            int j;
9458            for (j=0; j<NI; j++) {
9459                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9460                if (DEBUG_SHOW_INFO) {
9461                    Log.v(TAG, "    IntentFilter:");
9462                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9463                }
9464                removeFilter(intent);
9465            }
9466        }
9467
9468        @Override
9469        protected boolean allowFilterResult(
9470                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9471            ServiceInfo filterSi = filter.service.info;
9472            for (int i=dest.size()-1; i>=0; i--) {
9473                ServiceInfo destAi = dest.get(i).serviceInfo;
9474                if (destAi.name == filterSi.name
9475                        && destAi.packageName == filterSi.packageName) {
9476                    return false;
9477                }
9478            }
9479            return true;
9480        }
9481
9482        @Override
9483        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9484            return new PackageParser.ServiceIntentInfo[size];
9485        }
9486
9487        @Override
9488        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9489            if (!sUserManager.exists(userId)) return true;
9490            PackageParser.Package p = filter.service.owner;
9491            if (p != null) {
9492                PackageSetting ps = (PackageSetting)p.mExtras;
9493                if (ps != null) {
9494                    // System apps are never considered stopped for purposes of
9495                    // filtering, because there may be no way for the user to
9496                    // actually re-launch them.
9497                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9498                            && ps.getStopped(userId);
9499                }
9500            }
9501            return false;
9502        }
9503
9504        @Override
9505        protected boolean isPackageForFilter(String packageName,
9506                PackageParser.ServiceIntentInfo info) {
9507            return packageName.equals(info.service.owner.packageName);
9508        }
9509
9510        @Override
9511        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9512                int match, int userId) {
9513            if (!sUserManager.exists(userId)) return null;
9514            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9515            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9516                return null;
9517            }
9518            final PackageParser.Service service = info.service;
9519            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9520            if (ps == null) {
9521                return null;
9522            }
9523            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9524                    ps.readUserState(userId), userId);
9525            if (si == null) {
9526                return null;
9527            }
9528            final ResolveInfo res = new ResolveInfo();
9529            res.serviceInfo = si;
9530            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9531                res.filter = filter;
9532            }
9533            res.priority = info.getPriority();
9534            res.preferredOrder = service.owner.mPreferredOrder;
9535            res.match = match;
9536            res.isDefault = info.hasDefault;
9537            res.labelRes = info.labelRes;
9538            res.nonLocalizedLabel = info.nonLocalizedLabel;
9539            res.icon = info.icon;
9540            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9541            return res;
9542        }
9543
9544        @Override
9545        protected void sortResults(List<ResolveInfo> results) {
9546            Collections.sort(results, mResolvePrioritySorter);
9547        }
9548
9549        @Override
9550        protected void dumpFilter(PrintWriter out, String prefix,
9551                PackageParser.ServiceIntentInfo filter) {
9552            out.print(prefix); out.print(
9553                    Integer.toHexString(System.identityHashCode(filter.service)));
9554                    out.print(' ');
9555                    filter.service.printComponentShortName(out);
9556                    out.print(" filter ");
9557                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9558        }
9559
9560        @Override
9561        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9562            return filter.service;
9563        }
9564
9565        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9566            PackageParser.Service service = (PackageParser.Service)label;
9567            out.print(prefix); out.print(
9568                    Integer.toHexString(System.identityHashCode(service)));
9569                    out.print(' ');
9570                    service.printComponentShortName(out);
9571            if (count > 1) {
9572                out.print(" ("); out.print(count); out.print(" filters)");
9573            }
9574            out.println();
9575        }
9576
9577//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9578//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9579//            final List<ResolveInfo> retList = Lists.newArrayList();
9580//            while (i.hasNext()) {
9581//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9582//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9583//                    retList.add(resolveInfo);
9584//                }
9585//            }
9586//            return retList;
9587//        }
9588
9589        // Keys are String (activity class name), values are Activity.
9590        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9591                = new ArrayMap<ComponentName, PackageParser.Service>();
9592        private int mFlags;
9593    };
9594
9595    private final class ProviderIntentResolver
9596            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9597        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9598                boolean defaultOnly, int userId) {
9599            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9600            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9601        }
9602
9603        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9604                int userId) {
9605            if (!sUserManager.exists(userId))
9606                return null;
9607            mFlags = flags;
9608            return super.queryIntent(intent, resolvedType,
9609                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9610        }
9611
9612        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9613                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9614            if (!sUserManager.exists(userId))
9615                return null;
9616            if (packageProviders == null) {
9617                return null;
9618            }
9619            mFlags = flags;
9620            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9621            final int N = packageProviders.size();
9622            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9623                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9624
9625            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9626            for (int i = 0; i < N; ++i) {
9627                intentFilters = packageProviders.get(i).intents;
9628                if (intentFilters != null && intentFilters.size() > 0) {
9629                    PackageParser.ProviderIntentInfo[] array =
9630                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9631                    intentFilters.toArray(array);
9632                    listCut.add(array);
9633                }
9634            }
9635            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9636        }
9637
9638        public final void addProvider(PackageParser.Provider p) {
9639            if (mProviders.containsKey(p.getComponentName())) {
9640                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9641                return;
9642            }
9643
9644            mProviders.put(p.getComponentName(), p);
9645            if (DEBUG_SHOW_INFO) {
9646                Log.v(TAG, "  "
9647                        + (p.info.nonLocalizedLabel != null
9648                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9649                Log.v(TAG, "    Class=" + p.info.name);
9650            }
9651            final int NI = p.intents.size();
9652            int j;
9653            for (j = 0; j < NI; j++) {
9654                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9655                if (DEBUG_SHOW_INFO) {
9656                    Log.v(TAG, "    IntentFilter:");
9657                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9658                }
9659                if (!intent.debugCheck()) {
9660                    Log.w(TAG, "==> For Provider " + p.info.name);
9661                }
9662                addFilter(intent);
9663            }
9664        }
9665
9666        public final void removeProvider(PackageParser.Provider p) {
9667            mProviders.remove(p.getComponentName());
9668            if (DEBUG_SHOW_INFO) {
9669                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9670                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9671                Log.v(TAG, "    Class=" + p.info.name);
9672            }
9673            final int NI = p.intents.size();
9674            int j;
9675            for (j = 0; j < NI; j++) {
9676                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9677                if (DEBUG_SHOW_INFO) {
9678                    Log.v(TAG, "    IntentFilter:");
9679                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9680                }
9681                removeFilter(intent);
9682            }
9683        }
9684
9685        @Override
9686        protected boolean allowFilterResult(
9687                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9688            ProviderInfo filterPi = filter.provider.info;
9689            for (int i = dest.size() - 1; i >= 0; i--) {
9690                ProviderInfo destPi = dest.get(i).providerInfo;
9691                if (destPi.name == filterPi.name
9692                        && destPi.packageName == filterPi.packageName) {
9693                    return false;
9694                }
9695            }
9696            return true;
9697        }
9698
9699        @Override
9700        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9701            return new PackageParser.ProviderIntentInfo[size];
9702        }
9703
9704        @Override
9705        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9706            if (!sUserManager.exists(userId))
9707                return true;
9708            PackageParser.Package p = filter.provider.owner;
9709            if (p != null) {
9710                PackageSetting ps = (PackageSetting) p.mExtras;
9711                if (ps != null) {
9712                    // System apps are never considered stopped for purposes of
9713                    // filtering, because there may be no way for the user to
9714                    // actually re-launch them.
9715                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9716                            && ps.getStopped(userId);
9717                }
9718            }
9719            return false;
9720        }
9721
9722        @Override
9723        protected boolean isPackageForFilter(String packageName,
9724                PackageParser.ProviderIntentInfo info) {
9725            return packageName.equals(info.provider.owner.packageName);
9726        }
9727
9728        @Override
9729        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9730                int match, int userId) {
9731            if (!sUserManager.exists(userId))
9732                return null;
9733            final PackageParser.ProviderIntentInfo info = filter;
9734            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9735                return null;
9736            }
9737            final PackageParser.Provider provider = info.provider;
9738            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9739            if (ps == null) {
9740                return null;
9741            }
9742            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9743                    ps.readUserState(userId), userId);
9744            if (pi == null) {
9745                return null;
9746            }
9747            final ResolveInfo res = new ResolveInfo();
9748            res.providerInfo = pi;
9749            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9750                res.filter = filter;
9751            }
9752            res.priority = info.getPriority();
9753            res.preferredOrder = provider.owner.mPreferredOrder;
9754            res.match = match;
9755            res.isDefault = info.hasDefault;
9756            res.labelRes = info.labelRes;
9757            res.nonLocalizedLabel = info.nonLocalizedLabel;
9758            res.icon = info.icon;
9759            res.system = res.providerInfo.applicationInfo.isSystemApp();
9760            return res;
9761        }
9762
9763        @Override
9764        protected void sortResults(List<ResolveInfo> results) {
9765            Collections.sort(results, mResolvePrioritySorter);
9766        }
9767
9768        @Override
9769        protected void dumpFilter(PrintWriter out, String prefix,
9770                PackageParser.ProviderIntentInfo filter) {
9771            out.print(prefix);
9772            out.print(
9773                    Integer.toHexString(System.identityHashCode(filter.provider)));
9774            out.print(' ');
9775            filter.provider.printComponentShortName(out);
9776            out.print(" filter ");
9777            out.println(Integer.toHexString(System.identityHashCode(filter)));
9778        }
9779
9780        @Override
9781        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9782            return filter.provider;
9783        }
9784
9785        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9786            PackageParser.Provider provider = (PackageParser.Provider)label;
9787            out.print(prefix); out.print(
9788                    Integer.toHexString(System.identityHashCode(provider)));
9789                    out.print(' ');
9790                    provider.printComponentShortName(out);
9791            if (count > 1) {
9792                out.print(" ("); out.print(count); out.print(" filters)");
9793            }
9794            out.println();
9795        }
9796
9797        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9798                = new ArrayMap<ComponentName, PackageParser.Provider>();
9799        private int mFlags;
9800    }
9801
9802    private static final class EphemeralIntentResolver
9803            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9804        @Override
9805        protected EphemeralResolveIntentInfo[] newArray(int size) {
9806            return new EphemeralResolveIntentInfo[size];
9807        }
9808
9809        @Override
9810        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9811            return true;
9812        }
9813
9814        @Override
9815        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9816                int userId) {
9817            if (!sUserManager.exists(userId)) {
9818                return null;
9819            }
9820            return info.getEphemeralResolveInfo();
9821        }
9822    }
9823
9824    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9825            new Comparator<ResolveInfo>() {
9826        public int compare(ResolveInfo r1, ResolveInfo r2) {
9827            int v1 = r1.priority;
9828            int v2 = r2.priority;
9829            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9830            if (v1 != v2) {
9831                return (v1 > v2) ? -1 : 1;
9832            }
9833            v1 = r1.preferredOrder;
9834            v2 = r2.preferredOrder;
9835            if (v1 != v2) {
9836                return (v1 > v2) ? -1 : 1;
9837            }
9838            if (r1.isDefault != r2.isDefault) {
9839                return r1.isDefault ? -1 : 1;
9840            }
9841            v1 = r1.match;
9842            v2 = r2.match;
9843            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9844            if (v1 != v2) {
9845                return (v1 > v2) ? -1 : 1;
9846            }
9847            if (r1.system != r2.system) {
9848                return r1.system ? -1 : 1;
9849            }
9850            if (r1.activityInfo != null) {
9851                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9852            }
9853            if (r1.serviceInfo != null) {
9854                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9855            }
9856            if (r1.providerInfo != null) {
9857                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9858            }
9859            return 0;
9860        }
9861    };
9862
9863    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9864            new Comparator<ProviderInfo>() {
9865        public int compare(ProviderInfo p1, ProviderInfo p2) {
9866            final int v1 = p1.initOrder;
9867            final int v2 = p2.initOrder;
9868            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9869        }
9870    };
9871
9872    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9873            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9874            final int[] userIds) {
9875        mHandler.post(new Runnable() {
9876            @Override
9877            public void run() {
9878                try {
9879                    final IActivityManager am = ActivityManagerNative.getDefault();
9880                    if (am == null) return;
9881                    final int[] resolvedUserIds;
9882                    if (userIds == null) {
9883                        resolvedUserIds = am.getRunningUserIds();
9884                    } else {
9885                        resolvedUserIds = userIds;
9886                    }
9887                    for (int id : resolvedUserIds) {
9888                        final Intent intent = new Intent(action,
9889                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9890                        if (extras != null) {
9891                            intent.putExtras(extras);
9892                        }
9893                        if (targetPkg != null) {
9894                            intent.setPackage(targetPkg);
9895                        }
9896                        // Modify the UID when posting to other users
9897                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9898                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9899                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9900                            intent.putExtra(Intent.EXTRA_UID, uid);
9901                        }
9902                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9903                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9904                        if (DEBUG_BROADCASTS) {
9905                            RuntimeException here = new RuntimeException("here");
9906                            here.fillInStackTrace();
9907                            Slog.d(TAG, "Sending to user " + id + ": "
9908                                    + intent.toShortString(false, true, false, false)
9909                                    + " " + intent.getExtras(), here);
9910                        }
9911                        am.broadcastIntent(null, intent, null, finishedReceiver,
9912                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9913                                null, finishedReceiver != null, false, id);
9914                    }
9915                } catch (RemoteException ex) {
9916                }
9917            }
9918        });
9919    }
9920
9921    /**
9922     * Check if the external storage media is available. This is true if there
9923     * is a mounted external storage medium or if the external storage is
9924     * emulated.
9925     */
9926    private boolean isExternalMediaAvailable() {
9927        return mMediaMounted || Environment.isExternalStorageEmulated();
9928    }
9929
9930    @Override
9931    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9932        // writer
9933        synchronized (mPackages) {
9934            if (!isExternalMediaAvailable()) {
9935                // If the external storage is no longer mounted at this point,
9936                // the caller may not have been able to delete all of this
9937                // packages files and can not delete any more.  Bail.
9938                return null;
9939            }
9940            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9941            if (lastPackage != null) {
9942                pkgs.remove(lastPackage);
9943            }
9944            if (pkgs.size() > 0) {
9945                return pkgs.get(0);
9946            }
9947        }
9948        return null;
9949    }
9950
9951    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9952        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9953                userId, andCode ? 1 : 0, packageName);
9954        if (mSystemReady) {
9955            msg.sendToTarget();
9956        } else {
9957            if (mPostSystemReadyMessages == null) {
9958                mPostSystemReadyMessages = new ArrayList<>();
9959            }
9960            mPostSystemReadyMessages.add(msg);
9961        }
9962    }
9963
9964    void startCleaningPackages() {
9965        // reader
9966        synchronized (mPackages) {
9967            if (!isExternalMediaAvailable()) {
9968                return;
9969            }
9970            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9971                return;
9972            }
9973        }
9974        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9975        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9976        IActivityManager am = ActivityManagerNative.getDefault();
9977        if (am != null) {
9978            try {
9979                am.startService(null, intent, null, mContext.getOpPackageName(),
9980                        UserHandle.USER_SYSTEM);
9981            } catch (RemoteException e) {
9982            }
9983        }
9984    }
9985
9986    @Override
9987    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9988            int installFlags, String installerPackageName, VerificationParams verificationParams,
9989            String packageAbiOverride) {
9990        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9991                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9992    }
9993
9994    @Override
9995    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9996            int installFlags, String installerPackageName, VerificationParams verificationParams,
9997            String packageAbiOverride, int userId) {
9998        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9999
10000        final int callingUid = Binder.getCallingUid();
10001        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10002
10003        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10004            try {
10005                if (observer != null) {
10006                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10007                }
10008            } catch (RemoteException re) {
10009            }
10010            return;
10011        }
10012
10013        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10014            installFlags |= PackageManager.INSTALL_FROM_ADB;
10015
10016        } else {
10017            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10018            // about installerPackageName.
10019
10020            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10021            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10022        }
10023
10024        UserHandle user;
10025        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10026            user = UserHandle.ALL;
10027        } else {
10028            user = new UserHandle(userId);
10029        }
10030
10031        // Only system components can circumvent runtime permissions when installing.
10032        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10033                && mContext.checkCallingOrSelfPermission(Manifest.permission
10034                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10035            throw new SecurityException("You need the "
10036                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10037                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10038        }
10039
10040        verificationParams.setInstallerUid(callingUid);
10041
10042        final File originFile = new File(originPath);
10043        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10044
10045        final Message msg = mHandler.obtainMessage(INIT_COPY);
10046        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10047                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10048        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10049        msg.obj = params;
10050
10051        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10052                System.identityHashCode(msg.obj));
10053        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10054                System.identityHashCode(msg.obj));
10055
10056        mHandler.sendMessage(msg);
10057    }
10058
10059    void installStage(String packageName, File stagedDir, String stagedCid,
10060            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10061            String installerPackageName, int installerUid, UserHandle user) {
10062        if (DEBUG_EPHEMERAL) {
10063            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10064                Slog.d(TAG, "Ephemeral install of " + packageName);
10065            }
10066        }
10067        final VerificationParams verifParams = new VerificationParams(
10068                null, sessionParams.originatingUri, sessionParams.referrerUri,
10069                sessionParams.originatingUid);
10070        verifParams.setInstallerUid(installerUid);
10071
10072        final OriginInfo origin;
10073        if (stagedDir != null) {
10074            origin = OriginInfo.fromStagedFile(stagedDir);
10075        } else {
10076            origin = OriginInfo.fromStagedContainer(stagedCid);
10077        }
10078
10079        final Message msg = mHandler.obtainMessage(INIT_COPY);
10080        final InstallParams params = new InstallParams(origin, null, observer,
10081                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10082                verifParams, user, sessionParams.abiOverride,
10083                sessionParams.grantedRuntimePermissions);
10084        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10085        msg.obj = params;
10086
10087        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10088                System.identityHashCode(msg.obj));
10089        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10090                System.identityHashCode(msg.obj));
10091
10092        mHandler.sendMessage(msg);
10093    }
10094
10095    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10096        Bundle extras = new Bundle(1);
10097        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10098
10099        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10100                packageName, extras, 0, null, null, new int[] {userId});
10101        try {
10102            IActivityManager am = ActivityManagerNative.getDefault();
10103            final boolean isSystem =
10104                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10105            if (isSystem && am.isUserRunning(userId, 0)) {
10106                // The just-installed/enabled app is bundled on the system, so presumed
10107                // to be able to run automatically without needing an explicit launch.
10108                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10109                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10110                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10111                        .setPackage(packageName);
10112                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10113                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10114            }
10115        } catch (RemoteException e) {
10116            // shouldn't happen
10117            Slog.w(TAG, "Unable to bootstrap installed package", e);
10118        }
10119    }
10120
10121    @Override
10122    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10123            int userId) {
10124        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10125        PackageSetting pkgSetting;
10126        final int uid = Binder.getCallingUid();
10127        enforceCrossUserPermission(uid, userId, true, true,
10128                "setApplicationHiddenSetting for user " + userId);
10129
10130        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10131            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10132            return false;
10133        }
10134
10135        long callingId = Binder.clearCallingIdentity();
10136        try {
10137            boolean sendAdded = false;
10138            boolean sendRemoved = false;
10139            // writer
10140            synchronized (mPackages) {
10141                pkgSetting = mSettings.mPackages.get(packageName);
10142                if (pkgSetting == null) {
10143                    return false;
10144                }
10145                if (pkgSetting.getHidden(userId) != hidden) {
10146                    pkgSetting.setHidden(hidden, userId);
10147                    mSettings.writePackageRestrictionsLPr(userId);
10148                    if (hidden) {
10149                        sendRemoved = true;
10150                    } else {
10151                        sendAdded = true;
10152                    }
10153                }
10154            }
10155            if (sendAdded) {
10156                sendPackageAddedForUser(packageName, pkgSetting, userId);
10157                return true;
10158            }
10159            if (sendRemoved) {
10160                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10161                        "hiding pkg");
10162                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10163                return true;
10164            }
10165        } finally {
10166            Binder.restoreCallingIdentity(callingId);
10167        }
10168        return false;
10169    }
10170
10171    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10172            int userId) {
10173        final PackageRemovedInfo info = new PackageRemovedInfo();
10174        info.removedPackage = packageName;
10175        info.removedUsers = new int[] {userId};
10176        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10177        info.sendBroadcast(false, false, false);
10178    }
10179
10180    /**
10181     * Returns true if application is not found or there was an error. Otherwise it returns
10182     * the hidden state of the package for the given user.
10183     */
10184    @Override
10185    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10186        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10187        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10188                false, "getApplicationHidden for user " + userId);
10189        PackageSetting pkgSetting;
10190        long callingId = Binder.clearCallingIdentity();
10191        try {
10192            // writer
10193            synchronized (mPackages) {
10194                pkgSetting = mSettings.mPackages.get(packageName);
10195                if (pkgSetting == null) {
10196                    return true;
10197                }
10198                return pkgSetting.getHidden(userId);
10199            }
10200        } finally {
10201            Binder.restoreCallingIdentity(callingId);
10202        }
10203    }
10204
10205    /**
10206     * @hide
10207     */
10208    @Override
10209    public int installExistingPackageAsUser(String packageName, int userId) {
10210        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10211                null);
10212        PackageSetting pkgSetting;
10213        final int uid = Binder.getCallingUid();
10214        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10215                + userId);
10216        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10217            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10218        }
10219
10220        long callingId = Binder.clearCallingIdentity();
10221        try {
10222            boolean sendAdded = false;
10223
10224            // writer
10225            synchronized (mPackages) {
10226                pkgSetting = mSettings.mPackages.get(packageName);
10227                if (pkgSetting == null) {
10228                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10229                }
10230                if (!pkgSetting.getInstalled(userId)) {
10231                    pkgSetting.setInstalled(true, userId);
10232                    pkgSetting.setHidden(false, userId);
10233                    mSettings.writePackageRestrictionsLPr(userId);
10234                    sendAdded = true;
10235                }
10236            }
10237
10238            if (sendAdded) {
10239                sendPackageAddedForUser(packageName, pkgSetting, userId);
10240            }
10241        } finally {
10242            Binder.restoreCallingIdentity(callingId);
10243        }
10244
10245        return PackageManager.INSTALL_SUCCEEDED;
10246    }
10247
10248    boolean isUserRestricted(int userId, String restrictionKey) {
10249        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10250        if (restrictions.getBoolean(restrictionKey, false)) {
10251            Log.w(TAG, "User is restricted: " + restrictionKey);
10252            return true;
10253        }
10254        return false;
10255    }
10256
10257    @Override
10258    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10259        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10260        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10261                "setPackageSuspended for user " + userId);
10262
10263        long callingId = Binder.clearCallingIdentity();
10264        try {
10265            synchronized (mPackages) {
10266                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10267                if (pkgSetting != null) {
10268                    if (pkgSetting.getSuspended(userId) != suspended) {
10269                        pkgSetting.setSuspended(suspended, userId);
10270                        mSettings.writePackageRestrictionsLPr(userId);
10271                    }
10272
10273                    // TODO:
10274                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10275                    // * remove app from recents (kill app it if it is running)
10276                    // * erase existing notifications for this app
10277                    return true;
10278                }
10279
10280                return false;
10281            }
10282        } finally {
10283            Binder.restoreCallingIdentity(callingId);
10284        }
10285    }
10286
10287    @Override
10288    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10289        mContext.enforceCallingOrSelfPermission(
10290                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10291                "Only package verification agents can verify applications");
10292
10293        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10294        final PackageVerificationResponse response = new PackageVerificationResponse(
10295                verificationCode, Binder.getCallingUid());
10296        msg.arg1 = id;
10297        msg.obj = response;
10298        mHandler.sendMessage(msg);
10299    }
10300
10301    @Override
10302    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10303            long millisecondsToDelay) {
10304        mContext.enforceCallingOrSelfPermission(
10305                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10306                "Only package verification agents can extend verification timeouts");
10307
10308        final PackageVerificationState state = mPendingVerification.get(id);
10309        final PackageVerificationResponse response = new PackageVerificationResponse(
10310                verificationCodeAtTimeout, Binder.getCallingUid());
10311
10312        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10313            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10314        }
10315        if (millisecondsToDelay < 0) {
10316            millisecondsToDelay = 0;
10317        }
10318        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10319                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10320            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10321        }
10322
10323        if ((state != null) && !state.timeoutExtended()) {
10324            state.extendTimeout();
10325
10326            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10327            msg.arg1 = id;
10328            msg.obj = response;
10329            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10330        }
10331    }
10332
10333    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10334            int verificationCode, UserHandle user) {
10335        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10336        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10337        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10338        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10339        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10340
10341        mContext.sendBroadcastAsUser(intent, user,
10342                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10343    }
10344
10345    private ComponentName matchComponentForVerifier(String packageName,
10346            List<ResolveInfo> receivers) {
10347        ActivityInfo targetReceiver = null;
10348
10349        final int NR = receivers.size();
10350        for (int i = 0; i < NR; i++) {
10351            final ResolveInfo info = receivers.get(i);
10352            if (info.activityInfo == null) {
10353                continue;
10354            }
10355
10356            if (packageName.equals(info.activityInfo.packageName)) {
10357                targetReceiver = info.activityInfo;
10358                break;
10359            }
10360        }
10361
10362        if (targetReceiver == null) {
10363            return null;
10364        }
10365
10366        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10367    }
10368
10369    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10370            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10371        if (pkgInfo.verifiers.length == 0) {
10372            return null;
10373        }
10374
10375        final int N = pkgInfo.verifiers.length;
10376        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10377        for (int i = 0; i < N; i++) {
10378            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10379
10380            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10381                    receivers);
10382            if (comp == null) {
10383                continue;
10384            }
10385
10386            final int verifierUid = getUidForVerifier(verifierInfo);
10387            if (verifierUid == -1) {
10388                continue;
10389            }
10390
10391            if (DEBUG_VERIFY) {
10392                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10393                        + " with the correct signature");
10394            }
10395            sufficientVerifiers.add(comp);
10396            verificationState.addSufficientVerifier(verifierUid);
10397        }
10398
10399        return sufficientVerifiers;
10400    }
10401
10402    private int getUidForVerifier(VerifierInfo verifierInfo) {
10403        synchronized (mPackages) {
10404            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10405            if (pkg == null) {
10406                return -1;
10407            } else if (pkg.mSignatures.length != 1) {
10408                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10409                        + " has more than one signature; ignoring");
10410                return -1;
10411            }
10412
10413            /*
10414             * If the public key of the package's signature does not match
10415             * our expected public key, then this is a different package and
10416             * we should skip.
10417             */
10418
10419            final byte[] expectedPublicKey;
10420            try {
10421                final Signature verifierSig = pkg.mSignatures[0];
10422                final PublicKey publicKey = verifierSig.getPublicKey();
10423                expectedPublicKey = publicKey.getEncoded();
10424            } catch (CertificateException e) {
10425                return -1;
10426            }
10427
10428            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10429
10430            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10431                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10432                        + " does not have the expected public key; ignoring");
10433                return -1;
10434            }
10435
10436            return pkg.applicationInfo.uid;
10437        }
10438    }
10439
10440    @Override
10441    public void finishPackageInstall(int token) {
10442        enforceSystemOrRoot("Only the system is allowed to finish installs");
10443
10444        if (DEBUG_INSTALL) {
10445            Slog.v(TAG, "BM finishing package install for " + token);
10446        }
10447        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10448
10449        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10450        mHandler.sendMessage(msg);
10451    }
10452
10453    /**
10454     * Get the verification agent timeout.
10455     *
10456     * @return verification timeout in milliseconds
10457     */
10458    private long getVerificationTimeout() {
10459        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10460                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10461                DEFAULT_VERIFICATION_TIMEOUT);
10462    }
10463
10464    /**
10465     * Get the default verification agent response code.
10466     *
10467     * @return default verification response code
10468     */
10469    private int getDefaultVerificationResponse() {
10470        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10471                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10472                DEFAULT_VERIFICATION_RESPONSE);
10473    }
10474
10475    /**
10476     * Check whether or not package verification has been enabled.
10477     *
10478     * @return true if verification should be performed
10479     */
10480    private boolean isVerificationEnabled(int userId, int installFlags) {
10481        if (!DEFAULT_VERIFY_ENABLE) {
10482            return false;
10483        }
10484        // Ephemeral apps don't get the full verification treatment
10485        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10486            if (DEBUG_EPHEMERAL) {
10487                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10488            }
10489            return false;
10490        }
10491
10492        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10493
10494        // Check if installing from ADB
10495        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10496            // Do not run verification in a test harness environment
10497            if (ActivityManager.isRunningInTestHarness()) {
10498                return false;
10499            }
10500            if (ensureVerifyAppsEnabled) {
10501                return true;
10502            }
10503            // Check if the developer does not want package verification for ADB installs
10504            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10505                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10506                return false;
10507            }
10508        }
10509
10510        if (ensureVerifyAppsEnabled) {
10511            return true;
10512        }
10513
10514        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10515                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10516    }
10517
10518    @Override
10519    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10520            throws RemoteException {
10521        mContext.enforceCallingOrSelfPermission(
10522                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10523                "Only intentfilter verification agents can verify applications");
10524
10525        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10526        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10527                Binder.getCallingUid(), verificationCode, failedDomains);
10528        msg.arg1 = id;
10529        msg.obj = response;
10530        mHandler.sendMessage(msg);
10531    }
10532
10533    @Override
10534    public int getIntentVerificationStatus(String packageName, int userId) {
10535        synchronized (mPackages) {
10536            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10537        }
10538    }
10539
10540    @Override
10541    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10542        mContext.enforceCallingOrSelfPermission(
10543                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10544
10545        boolean result = false;
10546        synchronized (mPackages) {
10547            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10548        }
10549        if (result) {
10550            scheduleWritePackageRestrictionsLocked(userId);
10551        }
10552        return result;
10553    }
10554
10555    @Override
10556    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10557        synchronized (mPackages) {
10558            return mSettings.getIntentFilterVerificationsLPr(packageName);
10559        }
10560    }
10561
10562    @Override
10563    public List<IntentFilter> getAllIntentFilters(String packageName) {
10564        if (TextUtils.isEmpty(packageName)) {
10565            return Collections.<IntentFilter>emptyList();
10566        }
10567        synchronized (mPackages) {
10568            PackageParser.Package pkg = mPackages.get(packageName);
10569            if (pkg == null || pkg.activities == null) {
10570                return Collections.<IntentFilter>emptyList();
10571            }
10572            final int count = pkg.activities.size();
10573            ArrayList<IntentFilter> result = new ArrayList<>();
10574            for (int n=0; n<count; n++) {
10575                PackageParser.Activity activity = pkg.activities.get(n);
10576                if (activity.intents != null && activity.intents.size() > 0) {
10577                    result.addAll(activity.intents);
10578                }
10579            }
10580            return result;
10581        }
10582    }
10583
10584    @Override
10585    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10586        mContext.enforceCallingOrSelfPermission(
10587                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10588
10589        synchronized (mPackages) {
10590            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10591            if (packageName != null) {
10592                result |= updateIntentVerificationStatus(packageName,
10593                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10594                        userId);
10595                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10596                        packageName, userId);
10597            }
10598            return result;
10599        }
10600    }
10601
10602    @Override
10603    public String getDefaultBrowserPackageName(int userId) {
10604        synchronized (mPackages) {
10605            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10606        }
10607    }
10608
10609    /**
10610     * Get the "allow unknown sources" setting.
10611     *
10612     * @return the current "allow unknown sources" setting
10613     */
10614    private int getUnknownSourcesSettings() {
10615        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10616                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10617                -1);
10618    }
10619
10620    @Override
10621    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10622        final int uid = Binder.getCallingUid();
10623        // writer
10624        synchronized (mPackages) {
10625            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10626            if (targetPackageSetting == null) {
10627                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10628            }
10629
10630            PackageSetting installerPackageSetting;
10631            if (installerPackageName != null) {
10632                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10633                if (installerPackageSetting == null) {
10634                    throw new IllegalArgumentException("Unknown installer package: "
10635                            + installerPackageName);
10636                }
10637            } else {
10638                installerPackageSetting = null;
10639            }
10640
10641            Signature[] callerSignature;
10642            Object obj = mSettings.getUserIdLPr(uid);
10643            if (obj != null) {
10644                if (obj instanceof SharedUserSetting) {
10645                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10646                } else if (obj instanceof PackageSetting) {
10647                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10648                } else {
10649                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10650                }
10651            } else {
10652                throw new SecurityException("Unknown calling UID: " + uid);
10653            }
10654
10655            // Verify: can't set installerPackageName to a package that is
10656            // not signed with the same cert as the caller.
10657            if (installerPackageSetting != null) {
10658                if (compareSignatures(callerSignature,
10659                        installerPackageSetting.signatures.mSignatures)
10660                        != PackageManager.SIGNATURE_MATCH) {
10661                    throw new SecurityException(
10662                            "Caller does not have same cert as new installer package "
10663                            + installerPackageName);
10664                }
10665            }
10666
10667            // Verify: if target already has an installer package, it must
10668            // be signed with the same cert as the caller.
10669            if (targetPackageSetting.installerPackageName != null) {
10670                PackageSetting setting = mSettings.mPackages.get(
10671                        targetPackageSetting.installerPackageName);
10672                // If the currently set package isn't valid, then it's always
10673                // okay to change it.
10674                if (setting != null) {
10675                    if (compareSignatures(callerSignature,
10676                            setting.signatures.mSignatures)
10677                            != PackageManager.SIGNATURE_MATCH) {
10678                        throw new SecurityException(
10679                                "Caller does not have same cert as old installer package "
10680                                + targetPackageSetting.installerPackageName);
10681                    }
10682                }
10683            }
10684
10685            // Okay!
10686            targetPackageSetting.installerPackageName = installerPackageName;
10687            scheduleWriteSettingsLocked();
10688        }
10689    }
10690
10691    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10692        // Queue up an async operation since the package installation may take a little while.
10693        mHandler.post(new Runnable() {
10694            public void run() {
10695                mHandler.removeCallbacks(this);
10696                 // Result object to be returned
10697                PackageInstalledInfo res = new PackageInstalledInfo();
10698                res.returnCode = currentStatus;
10699                res.uid = -1;
10700                res.pkg = null;
10701                res.removedInfo = new PackageRemovedInfo();
10702                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10703                    args.doPreInstall(res.returnCode);
10704                    synchronized (mInstallLock) {
10705                        installPackageTracedLI(args, res);
10706                    }
10707                    args.doPostInstall(res.returnCode, res.uid);
10708                }
10709
10710                // A restore should be performed at this point if (a) the install
10711                // succeeded, (b) the operation is not an update, and (c) the new
10712                // package has not opted out of backup participation.
10713                final boolean update = res.removedInfo.removedPackage != null;
10714                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10715                boolean doRestore = !update
10716                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10717
10718                // Set up the post-install work request bookkeeping.  This will be used
10719                // and cleaned up by the post-install event handling regardless of whether
10720                // there's a restore pass performed.  Token values are >= 1.
10721                int token;
10722                if (mNextInstallToken < 0) mNextInstallToken = 1;
10723                token = mNextInstallToken++;
10724
10725                PostInstallData data = new PostInstallData(args, res);
10726                mRunningInstalls.put(token, data);
10727                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10728
10729                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10730                    // Pass responsibility to the Backup Manager.  It will perform a
10731                    // restore if appropriate, then pass responsibility back to the
10732                    // Package Manager to run the post-install observer callbacks
10733                    // and broadcasts.
10734                    IBackupManager bm = IBackupManager.Stub.asInterface(
10735                            ServiceManager.getService(Context.BACKUP_SERVICE));
10736                    if (bm != null) {
10737                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10738                                + " to BM for possible restore");
10739                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10740                        try {
10741                            // TODO: http://b/22388012
10742                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10743                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10744                            } else {
10745                                doRestore = false;
10746                            }
10747                        } catch (RemoteException e) {
10748                            // can't happen; the backup manager is local
10749                        } catch (Exception e) {
10750                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10751                            doRestore = false;
10752                        }
10753                    } else {
10754                        Slog.e(TAG, "Backup Manager not found!");
10755                        doRestore = false;
10756                    }
10757                }
10758
10759                if (!doRestore) {
10760                    // No restore possible, or the Backup Manager was mysteriously not
10761                    // available -- just fire the post-install work request directly.
10762                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10763
10764                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10765
10766                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10767                    mHandler.sendMessage(msg);
10768                }
10769            }
10770        });
10771    }
10772
10773    private abstract class HandlerParams {
10774        private static final int MAX_RETRIES = 4;
10775
10776        /**
10777         * Number of times startCopy() has been attempted and had a non-fatal
10778         * error.
10779         */
10780        private int mRetries = 0;
10781
10782        /** User handle for the user requesting the information or installation. */
10783        private final UserHandle mUser;
10784        String traceMethod;
10785        int traceCookie;
10786
10787        HandlerParams(UserHandle user) {
10788            mUser = user;
10789        }
10790
10791        UserHandle getUser() {
10792            return mUser;
10793        }
10794
10795        HandlerParams setTraceMethod(String traceMethod) {
10796            this.traceMethod = traceMethod;
10797            return this;
10798        }
10799
10800        HandlerParams setTraceCookie(int traceCookie) {
10801            this.traceCookie = traceCookie;
10802            return this;
10803        }
10804
10805        final boolean startCopy() {
10806            boolean res;
10807            try {
10808                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10809
10810                if (++mRetries > MAX_RETRIES) {
10811                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10812                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10813                    handleServiceError();
10814                    return false;
10815                } else {
10816                    handleStartCopy();
10817                    res = true;
10818                }
10819            } catch (RemoteException e) {
10820                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10821                mHandler.sendEmptyMessage(MCS_RECONNECT);
10822                res = false;
10823            }
10824            handleReturnCode();
10825            return res;
10826        }
10827
10828        final void serviceError() {
10829            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10830            handleServiceError();
10831            handleReturnCode();
10832        }
10833
10834        abstract void handleStartCopy() throws RemoteException;
10835        abstract void handleServiceError();
10836        abstract void handleReturnCode();
10837    }
10838
10839    class MeasureParams extends HandlerParams {
10840        private final PackageStats mStats;
10841        private boolean mSuccess;
10842
10843        private final IPackageStatsObserver mObserver;
10844
10845        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10846            super(new UserHandle(stats.userHandle));
10847            mObserver = observer;
10848            mStats = stats;
10849        }
10850
10851        @Override
10852        public String toString() {
10853            return "MeasureParams{"
10854                + Integer.toHexString(System.identityHashCode(this))
10855                + " " + mStats.packageName + "}";
10856        }
10857
10858        @Override
10859        void handleStartCopy() throws RemoteException {
10860            synchronized (mInstallLock) {
10861                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10862            }
10863
10864            if (mSuccess) {
10865                final boolean mounted;
10866                if (Environment.isExternalStorageEmulated()) {
10867                    mounted = true;
10868                } else {
10869                    final String status = Environment.getExternalStorageState();
10870                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10871                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10872                }
10873
10874                if (mounted) {
10875                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10876
10877                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10878                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10879
10880                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10881                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10882
10883                    // Always subtract cache size, since it's a subdirectory
10884                    mStats.externalDataSize -= mStats.externalCacheSize;
10885
10886                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10887                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10888
10889                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10890                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10891                }
10892            }
10893        }
10894
10895        @Override
10896        void handleReturnCode() {
10897            if (mObserver != null) {
10898                try {
10899                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10900                } catch (RemoteException e) {
10901                    Slog.i(TAG, "Observer no longer exists.");
10902                }
10903            }
10904        }
10905
10906        @Override
10907        void handleServiceError() {
10908            Slog.e(TAG, "Could not measure application " + mStats.packageName
10909                            + " external storage");
10910        }
10911    }
10912
10913    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10914            throws RemoteException {
10915        long result = 0;
10916        for (File path : paths) {
10917            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10918        }
10919        return result;
10920    }
10921
10922    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10923        for (File path : paths) {
10924            try {
10925                mcs.clearDirectory(path.getAbsolutePath());
10926            } catch (RemoteException e) {
10927            }
10928        }
10929    }
10930
10931    static class OriginInfo {
10932        /**
10933         * Location where install is coming from, before it has been
10934         * copied/renamed into place. This could be a single monolithic APK
10935         * file, or a cluster directory. This location may be untrusted.
10936         */
10937        final File file;
10938        final String cid;
10939
10940        /**
10941         * Flag indicating that {@link #file} or {@link #cid} has already been
10942         * staged, meaning downstream users don't need to defensively copy the
10943         * contents.
10944         */
10945        final boolean staged;
10946
10947        /**
10948         * Flag indicating that {@link #file} or {@link #cid} is an already
10949         * installed app that is being moved.
10950         */
10951        final boolean existing;
10952
10953        final String resolvedPath;
10954        final File resolvedFile;
10955
10956        static OriginInfo fromNothing() {
10957            return new OriginInfo(null, null, false, false);
10958        }
10959
10960        static OriginInfo fromUntrustedFile(File file) {
10961            return new OriginInfo(file, null, false, false);
10962        }
10963
10964        static OriginInfo fromExistingFile(File file) {
10965            return new OriginInfo(file, null, false, true);
10966        }
10967
10968        static OriginInfo fromStagedFile(File file) {
10969            return new OriginInfo(file, null, true, false);
10970        }
10971
10972        static OriginInfo fromStagedContainer(String cid) {
10973            return new OriginInfo(null, cid, true, false);
10974        }
10975
10976        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10977            this.file = file;
10978            this.cid = cid;
10979            this.staged = staged;
10980            this.existing = existing;
10981
10982            if (cid != null) {
10983                resolvedPath = PackageHelper.getSdDir(cid);
10984                resolvedFile = new File(resolvedPath);
10985            } else if (file != null) {
10986                resolvedPath = file.getAbsolutePath();
10987                resolvedFile = file;
10988            } else {
10989                resolvedPath = null;
10990                resolvedFile = null;
10991            }
10992        }
10993    }
10994
10995    static class MoveInfo {
10996        final int moveId;
10997        final String fromUuid;
10998        final String toUuid;
10999        final String packageName;
11000        final String dataAppName;
11001        final int appId;
11002        final String seinfo;
11003
11004        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11005                String dataAppName, int appId, String seinfo) {
11006            this.moveId = moveId;
11007            this.fromUuid = fromUuid;
11008            this.toUuid = toUuid;
11009            this.packageName = packageName;
11010            this.dataAppName = dataAppName;
11011            this.appId = appId;
11012            this.seinfo = seinfo;
11013        }
11014    }
11015
11016    class InstallParams extends HandlerParams {
11017        final OriginInfo origin;
11018        final MoveInfo move;
11019        final IPackageInstallObserver2 observer;
11020        int installFlags;
11021        final String installerPackageName;
11022        final String volumeUuid;
11023        final VerificationParams verificationParams;
11024        private InstallArgs mArgs;
11025        private int mRet;
11026        final String packageAbiOverride;
11027        final String[] grantedRuntimePermissions;
11028
11029        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11030                int installFlags, String installerPackageName, String volumeUuid,
11031                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11032                String[] grantedPermissions) {
11033            super(user);
11034            this.origin = origin;
11035            this.move = move;
11036            this.observer = observer;
11037            this.installFlags = installFlags;
11038            this.installerPackageName = installerPackageName;
11039            this.volumeUuid = volumeUuid;
11040            this.verificationParams = verificationParams;
11041            this.packageAbiOverride = packageAbiOverride;
11042            this.grantedRuntimePermissions = grantedPermissions;
11043        }
11044
11045        @Override
11046        public String toString() {
11047            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11048                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11049        }
11050
11051        private int installLocationPolicy(PackageInfoLite pkgLite) {
11052            String packageName = pkgLite.packageName;
11053            int installLocation = pkgLite.installLocation;
11054            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11055            // reader
11056            synchronized (mPackages) {
11057                PackageParser.Package pkg = mPackages.get(packageName);
11058                if (pkg != null) {
11059                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11060                        // Check for downgrading.
11061                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11062                            try {
11063                                checkDowngrade(pkg, pkgLite);
11064                            } catch (PackageManagerException e) {
11065                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11066                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11067                            }
11068                        }
11069                        // Check for updated system application.
11070                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11071                            if (onSd) {
11072                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11073                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11074                            }
11075                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11076                        } else {
11077                            if (onSd) {
11078                                // Install flag overrides everything.
11079                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11080                            }
11081                            // If current upgrade specifies particular preference
11082                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11083                                // Application explicitly specified internal.
11084                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11085                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11086                                // App explictly prefers external. Let policy decide
11087                            } else {
11088                                // Prefer previous location
11089                                if (isExternal(pkg)) {
11090                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11091                                }
11092                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11093                            }
11094                        }
11095                    } else {
11096                        // Invalid install. Return error code
11097                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11098                    }
11099                }
11100            }
11101            // All the special cases have been taken care of.
11102            // Return result based on recommended install location.
11103            if (onSd) {
11104                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11105            }
11106            return pkgLite.recommendedInstallLocation;
11107        }
11108
11109        /*
11110         * Invoke remote method to get package information and install
11111         * location values. Override install location based on default
11112         * policy if needed and then create install arguments based
11113         * on the install location.
11114         */
11115        public void handleStartCopy() throws RemoteException {
11116            int ret = PackageManager.INSTALL_SUCCEEDED;
11117
11118            // If we're already staged, we've firmly committed to an install location
11119            if (origin.staged) {
11120                if (origin.file != null) {
11121                    installFlags |= PackageManager.INSTALL_INTERNAL;
11122                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11123                } else if (origin.cid != null) {
11124                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11125                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11126                } else {
11127                    throw new IllegalStateException("Invalid stage location");
11128                }
11129            }
11130
11131            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11132            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11133            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11134            PackageInfoLite pkgLite = null;
11135
11136            if (onInt && onSd) {
11137                // Check if both bits are set.
11138                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11139                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11140            } else if (onSd && ephemeral) {
11141                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11142                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11143            } else {
11144                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11145                        packageAbiOverride);
11146
11147                if (DEBUG_EPHEMERAL && ephemeral) {
11148                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11149                }
11150
11151                /*
11152                 * If we have too little free space, try to free cache
11153                 * before giving up.
11154                 */
11155                if (!origin.staged && pkgLite.recommendedInstallLocation
11156                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11157                    // TODO: focus freeing disk space on the target device
11158                    final StorageManager storage = StorageManager.from(mContext);
11159                    final long lowThreshold = storage.getStorageLowBytes(
11160                            Environment.getDataDirectory());
11161
11162                    final long sizeBytes = mContainerService.calculateInstalledSize(
11163                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11164
11165                    try {
11166                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11167                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11168                                installFlags, packageAbiOverride);
11169                    } catch (InstallerException e) {
11170                        Slog.w(TAG, "Failed to free cache", e);
11171                    }
11172
11173                    /*
11174                     * The cache free must have deleted the file we
11175                     * downloaded to install.
11176                     *
11177                     * TODO: fix the "freeCache" call to not delete
11178                     *       the file we care about.
11179                     */
11180                    if (pkgLite.recommendedInstallLocation
11181                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11182                        pkgLite.recommendedInstallLocation
11183                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11184                    }
11185                }
11186            }
11187
11188            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11189                int loc = pkgLite.recommendedInstallLocation;
11190                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11191                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11192                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11193                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11194                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11195                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11196                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11197                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11198                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11199                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11200                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11201                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11202                } else {
11203                    // Override with defaults if needed.
11204                    loc = installLocationPolicy(pkgLite);
11205                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11206                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11207                    } else if (!onSd && !onInt) {
11208                        // Override install location with flags
11209                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11210                            // Set the flag to install on external media.
11211                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11212                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11213                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11214                            if (DEBUG_EPHEMERAL) {
11215                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11216                            }
11217                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11218                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11219                                    |PackageManager.INSTALL_INTERNAL);
11220                        } else {
11221                            // Make sure the flag for installing on external
11222                            // media is unset
11223                            installFlags |= PackageManager.INSTALL_INTERNAL;
11224                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11225                        }
11226                    }
11227                }
11228            }
11229
11230            final InstallArgs args = createInstallArgs(this);
11231            mArgs = args;
11232
11233            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11234                // TODO: http://b/22976637
11235                // Apps installed for "all" users use the device owner to verify the app
11236                UserHandle verifierUser = getUser();
11237                if (verifierUser == UserHandle.ALL) {
11238                    verifierUser = UserHandle.SYSTEM;
11239                }
11240
11241                /*
11242                 * Determine if we have any installed package verifiers. If we
11243                 * do, then we'll defer to them to verify the packages.
11244                 */
11245                final int requiredUid = mRequiredVerifierPackage == null ? -1
11246                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11247                                verifierUser.getIdentifier());
11248                if (!origin.existing && requiredUid != -1
11249                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11250                    final Intent verification = new Intent(
11251                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11252                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11253                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11254                            PACKAGE_MIME_TYPE);
11255                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11256
11257                    // Query all live verifiers based on current user state
11258                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11259                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11260
11261                    if (DEBUG_VERIFY) {
11262                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11263                                + verification.toString() + " with " + pkgLite.verifiers.length
11264                                + " optional verifiers");
11265                    }
11266
11267                    final int verificationId = mPendingVerificationToken++;
11268
11269                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11270
11271                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11272                            installerPackageName);
11273
11274                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11275                            installFlags);
11276
11277                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11278                            pkgLite.packageName);
11279
11280                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11281                            pkgLite.versionCode);
11282
11283                    if (verificationParams != null) {
11284                        if (verificationParams.getVerificationURI() != null) {
11285                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11286                                 verificationParams.getVerificationURI());
11287                        }
11288                        if (verificationParams.getOriginatingURI() != null) {
11289                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11290                                  verificationParams.getOriginatingURI());
11291                        }
11292                        if (verificationParams.getReferrer() != null) {
11293                            verification.putExtra(Intent.EXTRA_REFERRER,
11294                                  verificationParams.getReferrer());
11295                        }
11296                        if (verificationParams.getOriginatingUid() >= 0) {
11297                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11298                                  verificationParams.getOriginatingUid());
11299                        }
11300                        if (verificationParams.getInstallerUid() >= 0) {
11301                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11302                                  verificationParams.getInstallerUid());
11303                        }
11304                    }
11305
11306                    final PackageVerificationState verificationState = new PackageVerificationState(
11307                            requiredUid, args);
11308
11309                    mPendingVerification.append(verificationId, verificationState);
11310
11311                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11312                            receivers, verificationState);
11313
11314                    /*
11315                     * If any sufficient verifiers were listed in the package
11316                     * manifest, attempt to ask them.
11317                     */
11318                    if (sufficientVerifiers != null) {
11319                        final int N = sufficientVerifiers.size();
11320                        if (N == 0) {
11321                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11322                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11323                        } else {
11324                            for (int i = 0; i < N; i++) {
11325                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11326
11327                                final Intent sufficientIntent = new Intent(verification);
11328                                sufficientIntent.setComponent(verifierComponent);
11329                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11330                            }
11331                        }
11332                    }
11333
11334                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11335                            mRequiredVerifierPackage, receivers);
11336                    if (ret == PackageManager.INSTALL_SUCCEEDED
11337                            && mRequiredVerifierPackage != null) {
11338                        Trace.asyncTraceBegin(
11339                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11340                        /*
11341                         * Send the intent to the required verification agent,
11342                         * but only start the verification timeout after the
11343                         * target BroadcastReceivers have run.
11344                         */
11345                        verification.setComponent(requiredVerifierComponent);
11346                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11347                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11348                                new BroadcastReceiver() {
11349                                    @Override
11350                                    public void onReceive(Context context, Intent intent) {
11351                                        final Message msg = mHandler
11352                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11353                                        msg.arg1 = verificationId;
11354                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11355                                    }
11356                                }, null, 0, null, null);
11357
11358                        /*
11359                         * We don't want the copy to proceed until verification
11360                         * succeeds, so null out this field.
11361                         */
11362                        mArgs = null;
11363                    }
11364                } else {
11365                    /*
11366                     * No package verification is enabled, so immediately start
11367                     * the remote call to initiate copy using temporary file.
11368                     */
11369                    ret = args.copyApk(mContainerService, true);
11370                }
11371            }
11372
11373            mRet = ret;
11374        }
11375
11376        @Override
11377        void handleReturnCode() {
11378            // If mArgs is null, then MCS couldn't be reached. When it
11379            // reconnects, it will try again to install. At that point, this
11380            // will succeed.
11381            if (mArgs != null) {
11382                processPendingInstall(mArgs, mRet);
11383            }
11384        }
11385
11386        @Override
11387        void handleServiceError() {
11388            mArgs = createInstallArgs(this);
11389            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11390        }
11391
11392        public boolean isForwardLocked() {
11393            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11394        }
11395    }
11396
11397    /**
11398     * Used during creation of InstallArgs
11399     *
11400     * @param installFlags package installation flags
11401     * @return true if should be installed on external storage
11402     */
11403    private static boolean installOnExternalAsec(int installFlags) {
11404        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11405            return false;
11406        }
11407        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11408            return true;
11409        }
11410        return false;
11411    }
11412
11413    /**
11414     * Used during creation of InstallArgs
11415     *
11416     * @param installFlags package installation flags
11417     * @return true if should be installed as forward locked
11418     */
11419    private static boolean installForwardLocked(int installFlags) {
11420        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11421    }
11422
11423    private InstallArgs createInstallArgs(InstallParams params) {
11424        if (params.move != null) {
11425            return new MoveInstallArgs(params);
11426        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11427            return new AsecInstallArgs(params);
11428        } else {
11429            return new FileInstallArgs(params);
11430        }
11431    }
11432
11433    /**
11434     * Create args that describe an existing installed package. Typically used
11435     * when cleaning up old installs, or used as a move source.
11436     */
11437    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11438            String resourcePath, String[] instructionSets) {
11439        final boolean isInAsec;
11440        if (installOnExternalAsec(installFlags)) {
11441            /* Apps on SD card are always in ASEC containers. */
11442            isInAsec = true;
11443        } else if (installForwardLocked(installFlags)
11444                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11445            /*
11446             * Forward-locked apps are only in ASEC containers if they're the
11447             * new style
11448             */
11449            isInAsec = true;
11450        } else {
11451            isInAsec = false;
11452        }
11453
11454        if (isInAsec) {
11455            return new AsecInstallArgs(codePath, instructionSets,
11456                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11457        } else {
11458            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11459        }
11460    }
11461
11462    static abstract class InstallArgs {
11463        /** @see InstallParams#origin */
11464        final OriginInfo origin;
11465        /** @see InstallParams#move */
11466        final MoveInfo move;
11467
11468        final IPackageInstallObserver2 observer;
11469        // Always refers to PackageManager flags only
11470        final int installFlags;
11471        final String installerPackageName;
11472        final String volumeUuid;
11473        final UserHandle user;
11474        final String abiOverride;
11475        final String[] installGrantPermissions;
11476        /** If non-null, drop an async trace when the install completes */
11477        final String traceMethod;
11478        final int traceCookie;
11479
11480        // The list of instruction sets supported by this app. This is currently
11481        // only used during the rmdex() phase to clean up resources. We can get rid of this
11482        // if we move dex files under the common app path.
11483        /* nullable */ String[] instructionSets;
11484
11485        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11486                int installFlags, String installerPackageName, String volumeUuid,
11487                UserHandle user, String[] instructionSets,
11488                String abiOverride, String[] installGrantPermissions,
11489                String traceMethod, int traceCookie) {
11490            this.origin = origin;
11491            this.move = move;
11492            this.installFlags = installFlags;
11493            this.observer = observer;
11494            this.installerPackageName = installerPackageName;
11495            this.volumeUuid = volumeUuid;
11496            this.user = user;
11497            this.instructionSets = instructionSets;
11498            this.abiOverride = abiOverride;
11499            this.installGrantPermissions = installGrantPermissions;
11500            this.traceMethod = traceMethod;
11501            this.traceCookie = traceCookie;
11502        }
11503
11504        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11505        abstract int doPreInstall(int status);
11506
11507        /**
11508         * Rename package into final resting place. All paths on the given
11509         * scanned package should be updated to reflect the rename.
11510         */
11511        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11512        abstract int doPostInstall(int status, int uid);
11513
11514        /** @see PackageSettingBase#codePathString */
11515        abstract String getCodePath();
11516        /** @see PackageSettingBase#resourcePathString */
11517        abstract String getResourcePath();
11518
11519        // Need installer lock especially for dex file removal.
11520        abstract void cleanUpResourcesLI();
11521        abstract boolean doPostDeleteLI(boolean delete);
11522
11523        /**
11524         * Called before the source arguments are copied. This is used mostly
11525         * for MoveParams when it needs to read the source file to put it in the
11526         * destination.
11527         */
11528        int doPreCopy() {
11529            return PackageManager.INSTALL_SUCCEEDED;
11530        }
11531
11532        /**
11533         * Called after the source arguments are copied. This is used mostly for
11534         * MoveParams when it needs to read the source file to put it in the
11535         * destination.
11536         *
11537         * @return
11538         */
11539        int doPostCopy(int uid) {
11540            return PackageManager.INSTALL_SUCCEEDED;
11541        }
11542
11543        protected boolean isFwdLocked() {
11544            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11545        }
11546
11547        protected boolean isExternalAsec() {
11548            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11549        }
11550
11551        protected boolean isEphemeral() {
11552            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11553        }
11554
11555        UserHandle getUser() {
11556            return user;
11557        }
11558    }
11559
11560    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11561        if (!allCodePaths.isEmpty()) {
11562            if (instructionSets == null) {
11563                throw new IllegalStateException("instructionSet == null");
11564            }
11565            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11566            for (String codePath : allCodePaths) {
11567                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11568                    try {
11569                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11570                    } catch (InstallerException ignored) {
11571                    }
11572                }
11573            }
11574        }
11575    }
11576
11577    /**
11578     * Logic to handle installation of non-ASEC applications, including copying
11579     * and renaming logic.
11580     */
11581    class FileInstallArgs extends InstallArgs {
11582        private File codeFile;
11583        private File resourceFile;
11584
11585        // Example topology:
11586        // /data/app/com.example/base.apk
11587        // /data/app/com.example/split_foo.apk
11588        // /data/app/com.example/lib/arm/libfoo.so
11589        // /data/app/com.example/lib/arm64/libfoo.so
11590        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11591
11592        /** New install */
11593        FileInstallArgs(InstallParams params) {
11594            super(params.origin, params.move, params.observer, params.installFlags,
11595                    params.installerPackageName, params.volumeUuid,
11596                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11597                    params.grantedRuntimePermissions,
11598                    params.traceMethod, params.traceCookie);
11599            if (isFwdLocked()) {
11600                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11601            }
11602        }
11603
11604        /** Existing install */
11605        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11606            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11607                    null, null, null, 0);
11608            this.codeFile = (codePath != null) ? new File(codePath) : null;
11609            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11610        }
11611
11612        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11613            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11614            try {
11615                return doCopyApk(imcs, temp);
11616            } finally {
11617                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11618            }
11619        }
11620
11621        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11622            if (origin.staged) {
11623                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11624                codeFile = origin.file;
11625                resourceFile = origin.file;
11626                return PackageManager.INSTALL_SUCCEEDED;
11627            }
11628
11629            try {
11630                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11631                final File tempDir =
11632                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11633                codeFile = tempDir;
11634                resourceFile = tempDir;
11635            } catch (IOException e) {
11636                Slog.w(TAG, "Failed to create copy file: " + e);
11637                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11638            }
11639
11640            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11641                @Override
11642                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11643                    if (!FileUtils.isValidExtFilename(name)) {
11644                        throw new IllegalArgumentException("Invalid filename: " + name);
11645                    }
11646                    try {
11647                        final File file = new File(codeFile, name);
11648                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11649                                O_RDWR | O_CREAT, 0644);
11650                        Os.chmod(file.getAbsolutePath(), 0644);
11651                        return new ParcelFileDescriptor(fd);
11652                    } catch (ErrnoException e) {
11653                        throw new RemoteException("Failed to open: " + e.getMessage());
11654                    }
11655                }
11656            };
11657
11658            int ret = PackageManager.INSTALL_SUCCEEDED;
11659            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11660            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11661                Slog.e(TAG, "Failed to copy package");
11662                return ret;
11663            }
11664
11665            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11666            NativeLibraryHelper.Handle handle = null;
11667            try {
11668                handle = NativeLibraryHelper.Handle.create(codeFile);
11669                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11670                        abiOverride);
11671            } catch (IOException e) {
11672                Slog.e(TAG, "Copying native libraries failed", e);
11673                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11674            } finally {
11675                IoUtils.closeQuietly(handle);
11676            }
11677
11678            return ret;
11679        }
11680
11681        int doPreInstall(int status) {
11682            if (status != PackageManager.INSTALL_SUCCEEDED) {
11683                cleanUp();
11684            }
11685            return status;
11686        }
11687
11688        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11689            if (status != PackageManager.INSTALL_SUCCEEDED) {
11690                cleanUp();
11691                return false;
11692            }
11693
11694            final File targetDir = codeFile.getParentFile();
11695            final File beforeCodeFile = codeFile;
11696            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11697
11698            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11699            try {
11700                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11701            } catch (ErrnoException e) {
11702                Slog.w(TAG, "Failed to rename", e);
11703                return false;
11704            }
11705
11706            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11707                Slog.w(TAG, "Failed to restorecon");
11708                return false;
11709            }
11710
11711            // Reflect the rename internally
11712            codeFile = afterCodeFile;
11713            resourceFile = afterCodeFile;
11714
11715            // Reflect the rename in scanned details
11716            pkg.codePath = afterCodeFile.getAbsolutePath();
11717            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11718                    pkg.baseCodePath);
11719            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11720                    pkg.splitCodePaths);
11721
11722            // Reflect the rename in app info
11723            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11724            pkg.applicationInfo.setCodePath(pkg.codePath);
11725            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11726            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11727            pkg.applicationInfo.setResourcePath(pkg.codePath);
11728            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11729            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11730
11731            return true;
11732        }
11733
11734        int doPostInstall(int status, int uid) {
11735            if (status != PackageManager.INSTALL_SUCCEEDED) {
11736                cleanUp();
11737            }
11738            return status;
11739        }
11740
11741        @Override
11742        String getCodePath() {
11743            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11744        }
11745
11746        @Override
11747        String getResourcePath() {
11748            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11749        }
11750
11751        private boolean cleanUp() {
11752            if (codeFile == null || !codeFile.exists()) {
11753                return false;
11754            }
11755
11756            removeCodePathLI(codeFile);
11757
11758            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11759                resourceFile.delete();
11760            }
11761
11762            return true;
11763        }
11764
11765        void cleanUpResourcesLI() {
11766            // Try enumerating all code paths before deleting
11767            List<String> allCodePaths = Collections.EMPTY_LIST;
11768            if (codeFile != null && codeFile.exists()) {
11769                try {
11770                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11771                    allCodePaths = pkg.getAllCodePaths();
11772                } catch (PackageParserException e) {
11773                    // Ignored; we tried our best
11774                }
11775            }
11776
11777            cleanUp();
11778            removeDexFiles(allCodePaths, instructionSets);
11779        }
11780
11781        boolean doPostDeleteLI(boolean delete) {
11782            // XXX err, shouldn't we respect the delete flag?
11783            cleanUpResourcesLI();
11784            return true;
11785        }
11786    }
11787
11788    private boolean isAsecExternal(String cid) {
11789        final String asecPath = PackageHelper.getSdFilesystem(cid);
11790        return !asecPath.startsWith(mAsecInternalPath);
11791    }
11792
11793    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11794            PackageManagerException {
11795        if (copyRet < 0) {
11796            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11797                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11798                throw new PackageManagerException(copyRet, message);
11799            }
11800        }
11801    }
11802
11803    /**
11804     * Extract the MountService "container ID" from the full code path of an
11805     * .apk.
11806     */
11807    static String cidFromCodePath(String fullCodePath) {
11808        int eidx = fullCodePath.lastIndexOf("/");
11809        String subStr1 = fullCodePath.substring(0, eidx);
11810        int sidx = subStr1.lastIndexOf("/");
11811        return subStr1.substring(sidx+1, eidx);
11812    }
11813
11814    /**
11815     * Logic to handle installation of ASEC applications, including copying and
11816     * renaming logic.
11817     */
11818    class AsecInstallArgs extends InstallArgs {
11819        static final String RES_FILE_NAME = "pkg.apk";
11820        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11821
11822        String cid;
11823        String packagePath;
11824        String resourcePath;
11825
11826        /** New install */
11827        AsecInstallArgs(InstallParams params) {
11828            super(params.origin, params.move, params.observer, params.installFlags,
11829                    params.installerPackageName, params.volumeUuid,
11830                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11831                    params.grantedRuntimePermissions,
11832                    params.traceMethod, params.traceCookie);
11833        }
11834
11835        /** Existing install */
11836        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11837                        boolean isExternal, boolean isForwardLocked) {
11838            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11839                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11840                    instructionSets, null, null, null, 0);
11841            // Hackily pretend we're still looking at a full code path
11842            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11843                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11844            }
11845
11846            // Extract cid from fullCodePath
11847            int eidx = fullCodePath.lastIndexOf("/");
11848            String subStr1 = fullCodePath.substring(0, eidx);
11849            int sidx = subStr1.lastIndexOf("/");
11850            cid = subStr1.substring(sidx+1, eidx);
11851            setMountPath(subStr1);
11852        }
11853
11854        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11855            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11856                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11857                    instructionSets, null, null, null, 0);
11858            this.cid = cid;
11859            setMountPath(PackageHelper.getSdDir(cid));
11860        }
11861
11862        void createCopyFile() {
11863            cid = mInstallerService.allocateExternalStageCidLegacy();
11864        }
11865
11866        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11867            if (origin.staged && origin.cid != null) {
11868                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11869                cid = origin.cid;
11870                setMountPath(PackageHelper.getSdDir(cid));
11871                return PackageManager.INSTALL_SUCCEEDED;
11872            }
11873
11874            if (temp) {
11875                createCopyFile();
11876            } else {
11877                /*
11878                 * Pre-emptively destroy the container since it's destroyed if
11879                 * copying fails due to it existing anyway.
11880                 */
11881                PackageHelper.destroySdDir(cid);
11882            }
11883
11884            final String newMountPath = imcs.copyPackageToContainer(
11885                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11886                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11887
11888            if (newMountPath != null) {
11889                setMountPath(newMountPath);
11890                return PackageManager.INSTALL_SUCCEEDED;
11891            } else {
11892                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11893            }
11894        }
11895
11896        @Override
11897        String getCodePath() {
11898            return packagePath;
11899        }
11900
11901        @Override
11902        String getResourcePath() {
11903            return resourcePath;
11904        }
11905
11906        int doPreInstall(int status) {
11907            if (status != PackageManager.INSTALL_SUCCEEDED) {
11908                // Destroy container
11909                PackageHelper.destroySdDir(cid);
11910            } else {
11911                boolean mounted = PackageHelper.isContainerMounted(cid);
11912                if (!mounted) {
11913                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11914                            Process.SYSTEM_UID);
11915                    if (newMountPath != null) {
11916                        setMountPath(newMountPath);
11917                    } else {
11918                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11919                    }
11920                }
11921            }
11922            return status;
11923        }
11924
11925        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11926            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11927            String newMountPath = null;
11928            if (PackageHelper.isContainerMounted(cid)) {
11929                // Unmount the container
11930                if (!PackageHelper.unMountSdDir(cid)) {
11931                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11932                    return false;
11933                }
11934            }
11935            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11936                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11937                        " which might be stale. Will try to clean up.");
11938                // Clean up the stale container and proceed to recreate.
11939                if (!PackageHelper.destroySdDir(newCacheId)) {
11940                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11941                    return false;
11942                }
11943                // Successfully cleaned up stale container. Try to rename again.
11944                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11945                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11946                            + " inspite of cleaning it up.");
11947                    return false;
11948                }
11949            }
11950            if (!PackageHelper.isContainerMounted(newCacheId)) {
11951                Slog.w(TAG, "Mounting container " + newCacheId);
11952                newMountPath = PackageHelper.mountSdDir(newCacheId,
11953                        getEncryptKey(), Process.SYSTEM_UID);
11954            } else {
11955                newMountPath = PackageHelper.getSdDir(newCacheId);
11956            }
11957            if (newMountPath == null) {
11958                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11959                return false;
11960            }
11961            Log.i(TAG, "Succesfully renamed " + cid +
11962                    " to " + newCacheId +
11963                    " at new path: " + newMountPath);
11964            cid = newCacheId;
11965
11966            final File beforeCodeFile = new File(packagePath);
11967            setMountPath(newMountPath);
11968            final File afterCodeFile = new File(packagePath);
11969
11970            // Reflect the rename in scanned details
11971            pkg.codePath = afterCodeFile.getAbsolutePath();
11972            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11973                    pkg.baseCodePath);
11974            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11975                    pkg.splitCodePaths);
11976
11977            // Reflect the rename in app info
11978            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11979            pkg.applicationInfo.setCodePath(pkg.codePath);
11980            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11981            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11982            pkg.applicationInfo.setResourcePath(pkg.codePath);
11983            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11984            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11985
11986            return true;
11987        }
11988
11989        private void setMountPath(String mountPath) {
11990            final File mountFile = new File(mountPath);
11991
11992            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11993            if (monolithicFile.exists()) {
11994                packagePath = monolithicFile.getAbsolutePath();
11995                if (isFwdLocked()) {
11996                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11997                } else {
11998                    resourcePath = packagePath;
11999                }
12000            } else {
12001                packagePath = mountFile.getAbsolutePath();
12002                resourcePath = packagePath;
12003            }
12004        }
12005
12006        int doPostInstall(int status, int uid) {
12007            if (status != PackageManager.INSTALL_SUCCEEDED) {
12008                cleanUp();
12009            } else {
12010                final int groupOwner;
12011                final String protectedFile;
12012                if (isFwdLocked()) {
12013                    groupOwner = UserHandle.getSharedAppGid(uid);
12014                    protectedFile = RES_FILE_NAME;
12015                } else {
12016                    groupOwner = -1;
12017                    protectedFile = null;
12018                }
12019
12020                if (uid < Process.FIRST_APPLICATION_UID
12021                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12022                    Slog.e(TAG, "Failed to finalize " + cid);
12023                    PackageHelper.destroySdDir(cid);
12024                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12025                }
12026
12027                boolean mounted = PackageHelper.isContainerMounted(cid);
12028                if (!mounted) {
12029                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12030                }
12031            }
12032            return status;
12033        }
12034
12035        private void cleanUp() {
12036            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12037
12038            // Destroy secure container
12039            PackageHelper.destroySdDir(cid);
12040        }
12041
12042        private List<String> getAllCodePaths() {
12043            final File codeFile = new File(getCodePath());
12044            if (codeFile != null && codeFile.exists()) {
12045                try {
12046                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12047                    return pkg.getAllCodePaths();
12048                } catch (PackageParserException e) {
12049                    // Ignored; we tried our best
12050                }
12051            }
12052            return Collections.EMPTY_LIST;
12053        }
12054
12055        void cleanUpResourcesLI() {
12056            // Enumerate all code paths before deleting
12057            cleanUpResourcesLI(getAllCodePaths());
12058        }
12059
12060        private void cleanUpResourcesLI(List<String> allCodePaths) {
12061            cleanUp();
12062            removeDexFiles(allCodePaths, instructionSets);
12063        }
12064
12065        String getPackageName() {
12066            return getAsecPackageName(cid);
12067        }
12068
12069        boolean doPostDeleteLI(boolean delete) {
12070            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12071            final List<String> allCodePaths = getAllCodePaths();
12072            boolean mounted = PackageHelper.isContainerMounted(cid);
12073            if (mounted) {
12074                // Unmount first
12075                if (PackageHelper.unMountSdDir(cid)) {
12076                    mounted = false;
12077                }
12078            }
12079            if (!mounted && delete) {
12080                cleanUpResourcesLI(allCodePaths);
12081            }
12082            return !mounted;
12083        }
12084
12085        @Override
12086        int doPreCopy() {
12087            if (isFwdLocked()) {
12088                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12089                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12090                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12091                }
12092            }
12093
12094            return PackageManager.INSTALL_SUCCEEDED;
12095        }
12096
12097        @Override
12098        int doPostCopy(int uid) {
12099            if (isFwdLocked()) {
12100                if (uid < Process.FIRST_APPLICATION_UID
12101                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12102                                RES_FILE_NAME)) {
12103                    Slog.e(TAG, "Failed to finalize " + cid);
12104                    PackageHelper.destroySdDir(cid);
12105                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12106                }
12107            }
12108
12109            return PackageManager.INSTALL_SUCCEEDED;
12110        }
12111    }
12112
12113    /**
12114     * Logic to handle movement of existing installed applications.
12115     */
12116    class MoveInstallArgs extends InstallArgs {
12117        private File codeFile;
12118        private File resourceFile;
12119
12120        /** New install */
12121        MoveInstallArgs(InstallParams params) {
12122            super(params.origin, params.move, params.observer, params.installFlags,
12123                    params.installerPackageName, params.volumeUuid,
12124                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12125                    params.grantedRuntimePermissions,
12126                    params.traceMethod, params.traceCookie);
12127        }
12128
12129        int copyApk(IMediaContainerService imcs, boolean temp) {
12130            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12131                    + move.fromUuid + " to " + move.toUuid);
12132            synchronized (mInstaller) {
12133                try {
12134                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12135                            move.dataAppName, move.appId, move.seinfo);
12136                } catch (InstallerException e) {
12137                    Slog.w(TAG, "Failed to move app", e);
12138                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12139                }
12140            }
12141
12142            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12143            resourceFile = codeFile;
12144            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12145
12146            return PackageManager.INSTALL_SUCCEEDED;
12147        }
12148
12149        int doPreInstall(int status) {
12150            if (status != PackageManager.INSTALL_SUCCEEDED) {
12151                cleanUp(move.toUuid);
12152            }
12153            return status;
12154        }
12155
12156        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12157            if (status != PackageManager.INSTALL_SUCCEEDED) {
12158                cleanUp(move.toUuid);
12159                return false;
12160            }
12161
12162            // Reflect the move in app info
12163            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12164            pkg.applicationInfo.setCodePath(pkg.codePath);
12165            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12166            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12167            pkg.applicationInfo.setResourcePath(pkg.codePath);
12168            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12169            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12170
12171            return true;
12172        }
12173
12174        int doPostInstall(int status, int uid) {
12175            if (status == PackageManager.INSTALL_SUCCEEDED) {
12176                cleanUp(move.fromUuid);
12177            } else {
12178                cleanUp(move.toUuid);
12179            }
12180            return status;
12181        }
12182
12183        @Override
12184        String getCodePath() {
12185            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12186        }
12187
12188        @Override
12189        String getResourcePath() {
12190            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12191        }
12192
12193        private boolean cleanUp(String volumeUuid) {
12194            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12195                    move.dataAppName);
12196            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12197            synchronized (mInstallLock) {
12198                // Clean up both app data and code
12199                removeDataDirsLI(volumeUuid, move.packageName);
12200                removeCodePathLI(codeFile);
12201            }
12202            return true;
12203        }
12204
12205        void cleanUpResourcesLI() {
12206            throw new UnsupportedOperationException();
12207        }
12208
12209        boolean doPostDeleteLI(boolean delete) {
12210            throw new UnsupportedOperationException();
12211        }
12212    }
12213
12214    static String getAsecPackageName(String packageCid) {
12215        int idx = packageCid.lastIndexOf("-");
12216        if (idx == -1) {
12217            return packageCid;
12218        }
12219        return packageCid.substring(0, idx);
12220    }
12221
12222    // Utility method used to create code paths based on package name and available index.
12223    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12224        String idxStr = "";
12225        int idx = 1;
12226        // Fall back to default value of idx=1 if prefix is not
12227        // part of oldCodePath
12228        if (oldCodePath != null) {
12229            String subStr = oldCodePath;
12230            // Drop the suffix right away
12231            if (suffix != null && subStr.endsWith(suffix)) {
12232                subStr = subStr.substring(0, subStr.length() - suffix.length());
12233            }
12234            // If oldCodePath already contains prefix find out the
12235            // ending index to either increment or decrement.
12236            int sidx = subStr.lastIndexOf(prefix);
12237            if (sidx != -1) {
12238                subStr = subStr.substring(sidx + prefix.length());
12239                if (subStr != null) {
12240                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12241                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12242                    }
12243                    try {
12244                        idx = Integer.parseInt(subStr);
12245                        if (idx <= 1) {
12246                            idx++;
12247                        } else {
12248                            idx--;
12249                        }
12250                    } catch(NumberFormatException e) {
12251                    }
12252                }
12253            }
12254        }
12255        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12256        return prefix + idxStr;
12257    }
12258
12259    private File getNextCodePath(File targetDir, String packageName) {
12260        int suffix = 1;
12261        File result;
12262        do {
12263            result = new File(targetDir, packageName + "-" + suffix);
12264            suffix++;
12265        } while (result.exists());
12266        return result;
12267    }
12268
12269    // Utility method that returns the relative package path with respect
12270    // to the installation directory. Like say for /data/data/com.test-1.apk
12271    // string com.test-1 is returned.
12272    static String deriveCodePathName(String codePath) {
12273        if (codePath == null) {
12274            return null;
12275        }
12276        final File codeFile = new File(codePath);
12277        final String name = codeFile.getName();
12278        if (codeFile.isDirectory()) {
12279            return name;
12280        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12281            final int lastDot = name.lastIndexOf('.');
12282            return name.substring(0, lastDot);
12283        } else {
12284            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12285            return null;
12286        }
12287    }
12288
12289    static class PackageInstalledInfo {
12290        String name;
12291        int uid;
12292        // The set of users that originally had this package installed.
12293        int[] origUsers;
12294        // The set of users that now have this package installed.
12295        int[] newUsers;
12296        PackageParser.Package pkg;
12297        int returnCode;
12298        String returnMsg;
12299        PackageRemovedInfo removedInfo;
12300
12301        public void setError(int code, String msg) {
12302            returnCode = code;
12303            returnMsg = msg;
12304            Slog.w(TAG, msg);
12305        }
12306
12307        public void setError(String msg, PackageParserException e) {
12308            returnCode = e.error;
12309            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12310            Slog.w(TAG, msg, e);
12311        }
12312
12313        public void setError(String msg, PackageManagerException e) {
12314            returnCode = e.error;
12315            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12316            Slog.w(TAG, msg, e);
12317        }
12318
12319        // In some error cases we want to convey more info back to the observer
12320        String origPackage;
12321        String origPermission;
12322    }
12323
12324    /*
12325     * Install a non-existing package.
12326     */
12327    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12328            UserHandle user, String installerPackageName, String volumeUuid,
12329            PackageInstalledInfo res) {
12330        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12331
12332        // Remember this for later, in case we need to rollback this install
12333        String pkgName = pkg.packageName;
12334
12335        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12336        // TODO: b/23350563
12337        final boolean dataDirExists = Environment
12338                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12339
12340        synchronized(mPackages) {
12341            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12342                // A package with the same name is already installed, though
12343                // it has been renamed to an older name.  The package we
12344                // are trying to install should be installed as an update to
12345                // the existing one, but that has not been requested, so bail.
12346                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12347                        + " without first uninstalling package running as "
12348                        + mSettings.mRenamedPackages.get(pkgName));
12349                return;
12350            }
12351            if (mPackages.containsKey(pkgName)) {
12352                // Don't allow installation over an existing package with the same name.
12353                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12354                        + " without first uninstalling.");
12355                return;
12356            }
12357        }
12358
12359        try {
12360            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12361                    System.currentTimeMillis(), user);
12362
12363            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12364            // delete the partially installed application. the data directory will have to be
12365            // restored if it was already existing
12366            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12367                // remove package from internal structures.  Note that we want deletePackageX to
12368                // delete the package data and cache directories that it created in
12369                // scanPackageLocked, unless those directories existed before we even tried to
12370                // install.
12371                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12372                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12373                                res.removedInfo, true);
12374            }
12375
12376        } catch (PackageManagerException e) {
12377            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12378        }
12379
12380        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12381    }
12382
12383    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12384        // Can't rotate keys during boot or if sharedUser.
12385        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12386                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12387            return false;
12388        }
12389        // app is using upgradeKeySets; make sure all are valid
12390        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12391        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12392        for (int i = 0; i < upgradeKeySets.length; i++) {
12393            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12394                Slog.wtf(TAG, "Package "
12395                         + (oldPs.name != null ? oldPs.name : "<null>")
12396                         + " contains upgrade-key-set reference to unknown key-set: "
12397                         + upgradeKeySets[i]
12398                         + " reverting to signatures check.");
12399                return false;
12400            }
12401        }
12402        return true;
12403    }
12404
12405    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12406        // Upgrade keysets are being used.  Determine if new package has a superset of the
12407        // required keys.
12408        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12409        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12410        for (int i = 0; i < upgradeKeySets.length; i++) {
12411            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12412            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12413                return true;
12414            }
12415        }
12416        return false;
12417    }
12418
12419    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12420            UserHandle user, String installerPackageName, String volumeUuid,
12421            PackageInstalledInfo res) {
12422        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12423
12424        final PackageParser.Package oldPackage;
12425        final String pkgName = pkg.packageName;
12426        final int[] allUsers;
12427        final boolean[] perUserInstalled;
12428
12429        // First find the old package info and check signatures
12430        synchronized(mPackages) {
12431            oldPackage = mPackages.get(pkgName);
12432            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12433            if (isEphemeral && !oldIsEphemeral) {
12434                // can't downgrade from full to ephemeral
12435                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12436                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12437                return;
12438            }
12439            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12440            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12441            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12442                if(!checkUpgradeKeySetLP(ps, pkg)) {
12443                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12444                            "New package not signed by keys specified by upgrade-keysets: "
12445                            + pkgName);
12446                    return;
12447                }
12448            } else {
12449                // default to original signature matching
12450                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12451                    != PackageManager.SIGNATURE_MATCH) {
12452                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12453                            "New package has a different signature: " + pkgName);
12454                    return;
12455                }
12456            }
12457
12458            // In case of rollback, remember per-user/profile install state
12459            allUsers = sUserManager.getUserIds();
12460            perUserInstalled = new boolean[allUsers.length];
12461            for (int i = 0; i < allUsers.length; i++) {
12462                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12463            }
12464        }
12465
12466        boolean sysPkg = (isSystemApp(oldPackage));
12467        if (sysPkg) {
12468            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12469                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12470        } else {
12471            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12472                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12473        }
12474    }
12475
12476    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12477            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12478            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12479            String volumeUuid, PackageInstalledInfo res) {
12480        String pkgName = deletedPackage.packageName;
12481        boolean deletedPkg = true;
12482        boolean updatedSettings = false;
12483
12484        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12485                + deletedPackage);
12486        long origUpdateTime;
12487        if (pkg.mExtras != null) {
12488            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12489        } else {
12490            origUpdateTime = 0;
12491        }
12492
12493        // First delete the existing package while retaining the data directory
12494        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12495                res.removedInfo, true)) {
12496            // If the existing package wasn't successfully deleted
12497            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12498            deletedPkg = false;
12499        } else {
12500            // Successfully deleted the old package; proceed with replace.
12501
12502            // If deleted package lived in a container, give users a chance to
12503            // relinquish resources before killing.
12504            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12505                if (DEBUG_INSTALL) {
12506                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12507                }
12508                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12509                final ArrayList<String> pkgList = new ArrayList<String>(1);
12510                pkgList.add(deletedPackage.applicationInfo.packageName);
12511                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12512            }
12513
12514            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12515            try {
12516                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12517                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12518                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12519                        perUserInstalled, res, user);
12520                updatedSettings = true;
12521            } catch (PackageManagerException e) {
12522                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12523            }
12524        }
12525
12526        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12527            // remove package from internal structures.  Note that we want deletePackageX to
12528            // delete the package data and cache directories that it created in
12529            // scanPackageLocked, unless those directories existed before we even tried to
12530            // install.
12531            if(updatedSettings) {
12532                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12533                deletePackageLI(
12534                        pkgName, null, true, allUsers, perUserInstalled,
12535                        PackageManager.DELETE_KEEP_DATA,
12536                                res.removedInfo, true);
12537            }
12538            // Since we failed to install the new package we need to restore the old
12539            // package that we deleted.
12540            if (deletedPkg) {
12541                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12542                File restoreFile = new File(deletedPackage.codePath);
12543                // Parse old package
12544                boolean oldExternal = isExternal(deletedPackage);
12545                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12546                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12547                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12548                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12549                try {
12550                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12551                            null);
12552                } catch (PackageManagerException e) {
12553                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12554                            + e.getMessage());
12555                    return;
12556                }
12557                // Restore of old package succeeded. Update permissions.
12558                // writer
12559                synchronized (mPackages) {
12560                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12561                            UPDATE_PERMISSIONS_ALL);
12562                    // can downgrade to reader
12563                    mSettings.writeLPr();
12564                }
12565                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12566            }
12567        }
12568    }
12569
12570    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12571            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12572            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12573            String volumeUuid, PackageInstalledInfo res) {
12574        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12575                + ", old=" + deletedPackage);
12576        boolean disabledSystem = false;
12577        boolean updatedSettings = false;
12578        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12579        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12580                != 0) {
12581            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12582        }
12583        String packageName = deletedPackage.packageName;
12584        if (packageName == null) {
12585            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12586                    "Attempt to delete null packageName.");
12587            return;
12588        }
12589        PackageParser.Package oldPkg;
12590        PackageSetting oldPkgSetting;
12591        // reader
12592        synchronized (mPackages) {
12593            oldPkg = mPackages.get(packageName);
12594            oldPkgSetting = mSettings.mPackages.get(packageName);
12595            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12596                    (oldPkgSetting == null)) {
12597                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12598                        "Couldn't find package " + packageName + " information");
12599                return;
12600            }
12601        }
12602
12603        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12604
12605        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12606        res.removedInfo.removedPackage = packageName;
12607        // Remove existing system package
12608        removePackageLI(oldPkgSetting, true);
12609        // writer
12610        synchronized (mPackages) {
12611            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12612            if (!disabledSystem && deletedPackage != null) {
12613                // We didn't need to disable the .apk as a current system package,
12614                // which means we are replacing another update that is already
12615                // installed.  We need to make sure to delete the older one's .apk.
12616                res.removedInfo.args = createInstallArgsForExisting(0,
12617                        deletedPackage.applicationInfo.getCodePath(),
12618                        deletedPackage.applicationInfo.getResourcePath(),
12619                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12620            } else {
12621                res.removedInfo.args = null;
12622            }
12623        }
12624
12625        // Successfully disabled the old package. Now proceed with re-installation
12626        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12627
12628        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12629        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12630
12631        PackageParser.Package newPackage = null;
12632        try {
12633            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12634            if (newPackage.mExtras != null) {
12635                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12636                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12637                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12638
12639                // is the update attempting to change shared user? that isn't going to work...
12640                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12641                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12642                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12643                            + " to " + newPkgSetting.sharedUser);
12644                    updatedSettings = true;
12645                }
12646            }
12647
12648            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12649                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12650                        perUserInstalled, res, user);
12651                updatedSettings = true;
12652            }
12653
12654        } catch (PackageManagerException e) {
12655            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12656        }
12657
12658        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12659            // Re installation failed. Restore old information
12660            // Remove new pkg information
12661            if (newPackage != null) {
12662                removeInstalledPackageLI(newPackage, true);
12663            }
12664            // Add back the old system package
12665            try {
12666                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12667            } catch (PackageManagerException e) {
12668                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12669            }
12670            // Restore the old system information in Settings
12671            synchronized (mPackages) {
12672                if (disabledSystem) {
12673                    mSettings.enableSystemPackageLPw(packageName);
12674                }
12675                if (updatedSettings) {
12676                    mSettings.setInstallerPackageName(packageName,
12677                            oldPkgSetting.installerPackageName);
12678                }
12679                mSettings.writeLPr();
12680            }
12681        }
12682    }
12683
12684    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12685        // Collect all used permissions in the UID
12686        ArraySet<String> usedPermissions = new ArraySet<>();
12687        final int packageCount = su.packages.size();
12688        for (int i = 0; i < packageCount; i++) {
12689            PackageSetting ps = su.packages.valueAt(i);
12690            if (ps.pkg == null) {
12691                continue;
12692            }
12693            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12694            for (int j = 0; j < requestedPermCount; j++) {
12695                String permission = ps.pkg.requestedPermissions.get(j);
12696                BasePermission bp = mSettings.mPermissions.get(permission);
12697                if (bp != null) {
12698                    usedPermissions.add(permission);
12699                }
12700            }
12701        }
12702
12703        PermissionsState permissionsState = su.getPermissionsState();
12704        // Prune install permissions
12705        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12706        final int installPermCount = installPermStates.size();
12707        for (int i = installPermCount - 1; i >= 0;  i--) {
12708            PermissionState permissionState = installPermStates.get(i);
12709            if (!usedPermissions.contains(permissionState.getName())) {
12710                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12711                if (bp != null) {
12712                    permissionsState.revokeInstallPermission(bp);
12713                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12714                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12715                }
12716            }
12717        }
12718
12719        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12720
12721        // Prune runtime permissions
12722        for (int userId : allUserIds) {
12723            List<PermissionState> runtimePermStates = permissionsState
12724                    .getRuntimePermissionStates(userId);
12725            final int runtimePermCount = runtimePermStates.size();
12726            for (int i = runtimePermCount - 1; i >= 0; i--) {
12727                PermissionState permissionState = runtimePermStates.get(i);
12728                if (!usedPermissions.contains(permissionState.getName())) {
12729                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12730                    if (bp != null) {
12731                        permissionsState.revokeRuntimePermission(bp, userId);
12732                        permissionsState.updatePermissionFlags(bp, userId,
12733                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12734                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12735                                runtimePermissionChangedUserIds, userId);
12736                    }
12737                }
12738            }
12739        }
12740
12741        return runtimePermissionChangedUserIds;
12742    }
12743
12744    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12745            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12746            UserHandle user) {
12747        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12748
12749        String pkgName = newPackage.packageName;
12750        synchronized (mPackages) {
12751            //write settings. the installStatus will be incomplete at this stage.
12752            //note that the new package setting would have already been
12753            //added to mPackages. It hasn't been persisted yet.
12754            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12755            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12756            mSettings.writeLPr();
12757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12758        }
12759
12760        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12761        synchronized (mPackages) {
12762            updatePermissionsLPw(newPackage.packageName, newPackage,
12763                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12764                            ? UPDATE_PERMISSIONS_ALL : 0));
12765            // For system-bundled packages, we assume that installing an upgraded version
12766            // of the package implies that the user actually wants to run that new code,
12767            // so we enable the package.
12768            PackageSetting ps = mSettings.mPackages.get(pkgName);
12769            if (ps != null) {
12770                if (isSystemApp(newPackage)) {
12771                    // NB: implicit assumption that system package upgrades apply to all users
12772                    if (DEBUG_INSTALL) {
12773                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12774                    }
12775                    if (res.origUsers != null) {
12776                        for (int userHandle : res.origUsers) {
12777                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12778                                    userHandle, installerPackageName);
12779                        }
12780                    }
12781                    // Also convey the prior install/uninstall state
12782                    if (allUsers != null && perUserInstalled != null) {
12783                        for (int i = 0; i < allUsers.length; i++) {
12784                            if (DEBUG_INSTALL) {
12785                                Slog.d(TAG, "    user " + allUsers[i]
12786                                        + " => " + perUserInstalled[i]);
12787                            }
12788                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12789                        }
12790                        // these install state changes will be persisted in the
12791                        // upcoming call to mSettings.writeLPr().
12792                    }
12793                }
12794                // It's implied that when a user requests installation, they want the app to be
12795                // installed and enabled.
12796                int userId = user.getIdentifier();
12797                if (userId != UserHandle.USER_ALL) {
12798                    ps.setInstalled(true, userId);
12799                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12800                }
12801            }
12802            res.name = pkgName;
12803            res.uid = newPackage.applicationInfo.uid;
12804            res.pkg = newPackage;
12805            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12806            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12807            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12808            //to update install status
12809            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12810            mSettings.writeLPr();
12811            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12812        }
12813
12814        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12815    }
12816
12817    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12818        try {
12819            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12820            installPackageLI(args, res);
12821        } finally {
12822            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12823        }
12824    }
12825
12826    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12827        final int installFlags = args.installFlags;
12828        final String installerPackageName = args.installerPackageName;
12829        final String volumeUuid = args.volumeUuid;
12830        final File tmpPackageFile = new File(args.getCodePath());
12831        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12832        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12833                || (args.volumeUuid != null));
12834        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12835        boolean replace = false;
12836        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12837        if (args.move != null) {
12838            // moving a complete application; perfom an initial scan on the new install location
12839            scanFlags |= SCAN_INITIAL;
12840        }
12841        // Result object to be returned
12842        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12843
12844        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12845
12846        // Sanity check
12847        if (ephemeral && (forwardLocked || onExternal)) {
12848            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12849                    + " external=" + onExternal);
12850            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12851            return;
12852        }
12853
12854        // Retrieve PackageSettings and parse package
12855        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12856                | PackageParser.PARSE_ENFORCE_CODE
12857                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12858                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12859                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12860        PackageParser pp = new PackageParser();
12861        pp.setSeparateProcesses(mSeparateProcesses);
12862        pp.setDisplayMetrics(mMetrics);
12863
12864        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12865        final PackageParser.Package pkg;
12866        try {
12867            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12868        } catch (PackageParserException e) {
12869            res.setError("Failed parse during installPackageLI", e);
12870            return;
12871        } finally {
12872            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12873        }
12874
12875        // Mark that we have an install time CPU ABI override.
12876        pkg.cpuAbiOverride = args.abiOverride;
12877
12878        String pkgName = res.name = pkg.packageName;
12879        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12880            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12881                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12882                return;
12883            }
12884        }
12885
12886        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12887        try {
12888            pp.collectCertificates(pkg, parseFlags);
12889        } catch (PackageParserException e) {
12890            res.setError("Failed collect during installPackageLI", e);
12891            return;
12892        } finally {
12893            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12894        }
12895
12896        // Get rid of all references to package scan path via parser.
12897        pp = null;
12898        String oldCodePath = null;
12899        boolean systemApp = false;
12900        synchronized (mPackages) {
12901            // Check if installing already existing package
12902            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12903                String oldName = mSettings.mRenamedPackages.get(pkgName);
12904                if (pkg.mOriginalPackages != null
12905                        && pkg.mOriginalPackages.contains(oldName)
12906                        && mPackages.containsKey(oldName)) {
12907                    // This package is derived from an original package,
12908                    // and this device has been updating from that original
12909                    // name.  We must continue using the original name, so
12910                    // rename the new package here.
12911                    pkg.setPackageName(oldName);
12912                    pkgName = pkg.packageName;
12913                    replace = true;
12914                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12915                            + oldName + " pkgName=" + pkgName);
12916                } else if (mPackages.containsKey(pkgName)) {
12917                    // This package, under its official name, already exists
12918                    // on the device; we should replace it.
12919                    replace = true;
12920                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12921                }
12922
12923                // Prevent apps opting out from runtime permissions
12924                if (replace) {
12925                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12926                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12927                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12928                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12929                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12930                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12931                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12932                                        + " doesn't support runtime permissions but the old"
12933                                        + " target SDK " + oldTargetSdk + " does.");
12934                        return;
12935                    }
12936                }
12937            }
12938
12939            PackageSetting ps = mSettings.mPackages.get(pkgName);
12940            if (ps != null) {
12941                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12942
12943                // Quick sanity check that we're signed correctly if updating;
12944                // we'll check this again later when scanning, but we want to
12945                // bail early here before tripping over redefined permissions.
12946                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12947                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12948                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12949                                + pkg.packageName + " upgrade keys do not match the "
12950                                + "previously installed version");
12951                        return;
12952                    }
12953                } else {
12954                    try {
12955                        verifySignaturesLP(ps, pkg);
12956                    } catch (PackageManagerException e) {
12957                        res.setError(e.error, e.getMessage());
12958                        return;
12959                    }
12960                }
12961
12962                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12963                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12964                    systemApp = (ps.pkg.applicationInfo.flags &
12965                            ApplicationInfo.FLAG_SYSTEM) != 0;
12966                }
12967                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12968            }
12969
12970            // Check whether the newly-scanned package wants to define an already-defined perm
12971            int N = pkg.permissions.size();
12972            for (int i = N-1; i >= 0; i--) {
12973                PackageParser.Permission perm = pkg.permissions.get(i);
12974                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12975                if (bp != null) {
12976                    // If the defining package is signed with our cert, it's okay.  This
12977                    // also includes the "updating the same package" case, of course.
12978                    // "updating same package" could also involve key-rotation.
12979                    final boolean sigsOk;
12980                    if (bp.sourcePackage.equals(pkg.packageName)
12981                            && (bp.packageSetting instanceof PackageSetting)
12982                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12983                                    scanFlags))) {
12984                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12985                    } else {
12986                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12987                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12988                    }
12989                    if (!sigsOk) {
12990                        // If the owning package is the system itself, we log but allow
12991                        // install to proceed; we fail the install on all other permission
12992                        // redefinitions.
12993                        if (!bp.sourcePackage.equals("android")) {
12994                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12995                                    + pkg.packageName + " attempting to redeclare permission "
12996                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12997                            res.origPermission = perm.info.name;
12998                            res.origPackage = bp.sourcePackage;
12999                            return;
13000                        } else {
13001                            Slog.w(TAG, "Package " + pkg.packageName
13002                                    + " attempting to redeclare system permission "
13003                                    + perm.info.name + "; ignoring new declaration");
13004                            pkg.permissions.remove(i);
13005                        }
13006                    }
13007                }
13008            }
13009
13010        }
13011
13012        if (systemApp) {
13013            if (onExternal) {
13014                // Abort update; system app can't be replaced with app on sdcard
13015                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13016                        "Cannot install updates to system apps on sdcard");
13017                return;
13018            } else if (ephemeral) {
13019                // Abort update; system app can't be replaced with an ephemeral app
13020                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13021                        "Cannot update a system app with an ephemeral app");
13022                return;
13023            }
13024        }
13025
13026        if (args.move != null) {
13027            // We did an in-place move, so dex is ready to roll
13028            scanFlags |= SCAN_NO_DEX;
13029            scanFlags |= SCAN_MOVE;
13030
13031            synchronized (mPackages) {
13032                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13033                if (ps == null) {
13034                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13035                            "Missing settings for moved package " + pkgName);
13036                }
13037
13038                // We moved the entire application as-is, so bring over the
13039                // previously derived ABI information.
13040                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13041                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13042            }
13043
13044        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13045            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13046            scanFlags |= SCAN_NO_DEX;
13047
13048            try {
13049                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13050                        true /* extract libs */);
13051            } catch (PackageManagerException pme) {
13052                Slog.e(TAG, "Error deriving application ABI", pme);
13053                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13054                return;
13055            }
13056        }
13057
13058        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13059            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13060            return;
13061        }
13062
13063        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13064
13065        if (replace) {
13066            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13067                    installerPackageName, volumeUuid, res);
13068        } else {
13069            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13070                    args.user, installerPackageName, volumeUuid, res);
13071        }
13072        synchronized (mPackages) {
13073            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13074            if (ps != null) {
13075                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13076            }
13077        }
13078    }
13079
13080    private void startIntentFilterVerifications(int userId, boolean replacing,
13081            PackageParser.Package pkg) {
13082        if (mIntentFilterVerifierComponent == null) {
13083            Slog.w(TAG, "No IntentFilter verification will not be done as "
13084                    + "there is no IntentFilterVerifier available!");
13085            return;
13086        }
13087
13088        final int verifierUid = getPackageUid(
13089                mIntentFilterVerifierComponent.getPackageName(),
13090                MATCH_DEBUG_TRIAGED_MISSING,
13091                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13092
13093        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13094        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13095        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13096        mHandler.sendMessage(msg);
13097    }
13098
13099    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13100            PackageParser.Package pkg) {
13101        int size = pkg.activities.size();
13102        if (size == 0) {
13103            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13104                    "No activity, so no need to verify any IntentFilter!");
13105            return;
13106        }
13107
13108        final boolean hasDomainURLs = hasDomainURLs(pkg);
13109        if (!hasDomainURLs) {
13110            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13111                    "No domain URLs, so no need to verify any IntentFilter!");
13112            return;
13113        }
13114
13115        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13116                + " if any IntentFilter from the " + size
13117                + " Activities needs verification ...");
13118
13119        int count = 0;
13120        final String packageName = pkg.packageName;
13121
13122        synchronized (mPackages) {
13123            // If this is a new install and we see that we've already run verification for this
13124            // package, we have nothing to do: it means the state was restored from backup.
13125            if (!replacing) {
13126                IntentFilterVerificationInfo ivi =
13127                        mSettings.getIntentFilterVerificationLPr(packageName);
13128                if (ivi != null) {
13129                    if (DEBUG_DOMAIN_VERIFICATION) {
13130                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13131                                + ivi.getStatusString());
13132                    }
13133                    return;
13134                }
13135            }
13136
13137            // If any filters need to be verified, then all need to be.
13138            boolean needToVerify = false;
13139            for (PackageParser.Activity a : pkg.activities) {
13140                for (ActivityIntentInfo filter : a.intents) {
13141                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13142                        if (DEBUG_DOMAIN_VERIFICATION) {
13143                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13144                        }
13145                        needToVerify = true;
13146                        break;
13147                    }
13148                }
13149            }
13150
13151            if (needToVerify) {
13152                final int verificationId = mIntentFilterVerificationToken++;
13153                for (PackageParser.Activity a : pkg.activities) {
13154                    for (ActivityIntentInfo filter : a.intents) {
13155                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13156                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13157                                    "Verification needed for IntentFilter:" + filter.toString());
13158                            mIntentFilterVerifier.addOneIntentFilterVerification(
13159                                    verifierUid, userId, verificationId, filter, packageName);
13160                            count++;
13161                        }
13162                    }
13163                }
13164            }
13165        }
13166
13167        if (count > 0) {
13168            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13169                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13170                    +  " for userId:" + userId);
13171            mIntentFilterVerifier.startVerifications(userId);
13172        } else {
13173            if (DEBUG_DOMAIN_VERIFICATION) {
13174                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13175            }
13176        }
13177    }
13178
13179    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13180        final ComponentName cn  = filter.activity.getComponentName();
13181        final String packageName = cn.getPackageName();
13182
13183        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13184                packageName);
13185        if (ivi == null) {
13186            return true;
13187        }
13188        int status = ivi.getStatus();
13189        switch (status) {
13190            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13191            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13192                return true;
13193
13194            default:
13195                // Nothing to do
13196                return false;
13197        }
13198    }
13199
13200    private static boolean isMultiArch(ApplicationInfo info) {
13201        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13202    }
13203
13204    private static boolean isExternal(PackageParser.Package pkg) {
13205        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13206    }
13207
13208    private static boolean isExternal(PackageSetting ps) {
13209        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13210    }
13211
13212    private static boolean isEphemeral(PackageParser.Package pkg) {
13213        return pkg.applicationInfo.isEphemeralApp();
13214    }
13215
13216    private static boolean isEphemeral(PackageSetting ps) {
13217        return ps.pkg != null && isEphemeral(ps.pkg);
13218    }
13219
13220    private static boolean isSystemApp(PackageParser.Package pkg) {
13221        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13222    }
13223
13224    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13225        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13226    }
13227
13228    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13229        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13230    }
13231
13232    private static boolean isSystemApp(PackageSetting ps) {
13233        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13234    }
13235
13236    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13237        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13238    }
13239
13240    private int packageFlagsToInstallFlags(PackageSetting ps) {
13241        int installFlags = 0;
13242        if (isEphemeral(ps)) {
13243            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13244        }
13245        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13246            // This existing package was an external ASEC install when we have
13247            // the external flag without a UUID
13248            installFlags |= PackageManager.INSTALL_EXTERNAL;
13249        }
13250        if (ps.isForwardLocked()) {
13251            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13252        }
13253        return installFlags;
13254    }
13255
13256    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13257        if (isExternal(pkg)) {
13258            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13259                return StorageManager.UUID_PRIMARY_PHYSICAL;
13260            } else {
13261                return pkg.volumeUuid;
13262            }
13263        } else {
13264            return StorageManager.UUID_PRIVATE_INTERNAL;
13265        }
13266    }
13267
13268    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13269        if (isExternal(pkg)) {
13270            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13271                return mSettings.getExternalVersion();
13272            } else {
13273                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13274            }
13275        } else {
13276            return mSettings.getInternalVersion();
13277        }
13278    }
13279
13280    private void deleteTempPackageFiles() {
13281        final FilenameFilter filter = new FilenameFilter() {
13282            public boolean accept(File dir, String name) {
13283                return name.startsWith("vmdl") && name.endsWith(".tmp");
13284            }
13285        };
13286        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13287            file.delete();
13288        }
13289    }
13290
13291    @Override
13292    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13293            int flags) {
13294        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13295                flags);
13296    }
13297
13298    @Override
13299    public void deletePackage(final String packageName,
13300            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13301        mContext.enforceCallingOrSelfPermission(
13302                android.Manifest.permission.DELETE_PACKAGES, null);
13303        Preconditions.checkNotNull(packageName);
13304        Preconditions.checkNotNull(observer);
13305        final int uid = Binder.getCallingUid();
13306        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13307        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13308        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13309            mContext.enforceCallingOrSelfPermission(
13310                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13311                    "deletePackage for user " + userId);
13312        }
13313
13314        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13315            try {
13316                observer.onPackageDeleted(packageName,
13317                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13318            } catch (RemoteException re) {
13319            }
13320            return;
13321        }
13322
13323        for (int currentUserId : users) {
13324            if (getBlockUninstallForUser(packageName, currentUserId)) {
13325                try {
13326                    observer.onPackageDeleted(packageName,
13327                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13328                } catch (RemoteException re) {
13329                }
13330                return;
13331            }
13332        }
13333
13334        if (DEBUG_REMOVE) {
13335            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13336        }
13337        // Queue up an async operation since the package deletion may take a little while.
13338        mHandler.post(new Runnable() {
13339            public void run() {
13340                mHandler.removeCallbacks(this);
13341                final int returnCode = deletePackageX(packageName, userId, flags);
13342                try {
13343                    observer.onPackageDeleted(packageName, returnCode, null);
13344                } catch (RemoteException e) {
13345                    Log.i(TAG, "Observer no longer exists.");
13346                } //end catch
13347            } //end run
13348        });
13349    }
13350
13351    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13352        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13353                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13354        try {
13355            if (dpm != null) {
13356                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13357                        /* callingUserOnly =*/ false);
13358                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13359                        : deviceOwnerComponentName.getPackageName();
13360                // Does the package contains the device owner?
13361                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13362                // this check is probably not needed, since DO should be registered as a device
13363                // admin on some user too. (Original bug for this: b/17657954)
13364                if (packageName.equals(deviceOwnerPackageName)) {
13365                    return true;
13366                }
13367                // Does it contain a device admin for any user?
13368                int[] users;
13369                if (userId == UserHandle.USER_ALL) {
13370                    users = sUserManager.getUserIds();
13371                } else {
13372                    users = new int[]{userId};
13373                }
13374                for (int i = 0; i < users.length; ++i) {
13375                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13376                        return true;
13377                    }
13378                }
13379            }
13380        } catch (RemoteException e) {
13381        }
13382        return false;
13383    }
13384
13385    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13386        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13387    }
13388
13389    /**
13390     *  This method is an internal method that could be get invoked either
13391     *  to delete an installed package or to clean up a failed installation.
13392     *  After deleting an installed package, a broadcast is sent to notify any
13393     *  listeners that the package has been installed. For cleaning up a failed
13394     *  installation, the broadcast is not necessary since the package's
13395     *  installation wouldn't have sent the initial broadcast either
13396     *  The key steps in deleting a package are
13397     *  deleting the package information in internal structures like mPackages,
13398     *  deleting the packages base directories through installd
13399     *  updating mSettings to reflect current status
13400     *  persisting settings for later use
13401     *  sending a broadcast if necessary
13402     */
13403    private int deletePackageX(String packageName, int userId, int flags) {
13404        final PackageRemovedInfo info = new PackageRemovedInfo();
13405        final boolean res;
13406
13407        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13408                ? UserHandle.ALL : new UserHandle(userId);
13409
13410        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13411            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13412            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13413        }
13414
13415        boolean removedForAllUsers = false;
13416        boolean systemUpdate = false;
13417
13418        PackageParser.Package uninstalledPkg;
13419
13420        // for the uninstall-updates case and restricted profiles, remember the per-
13421        // userhandle installed state
13422        int[] allUsers;
13423        boolean[] perUserInstalled;
13424        synchronized (mPackages) {
13425            uninstalledPkg = mPackages.get(packageName);
13426            PackageSetting ps = mSettings.mPackages.get(packageName);
13427            allUsers = sUserManager.getUserIds();
13428            perUserInstalled = new boolean[allUsers.length];
13429            for (int i = 0; i < allUsers.length; i++) {
13430                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13431            }
13432        }
13433
13434        synchronized (mInstallLock) {
13435            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13436            res = deletePackageLI(packageName, removeForUser,
13437                    true, allUsers, perUserInstalled,
13438                    flags | REMOVE_CHATTY, info, true);
13439            systemUpdate = info.isRemovedPackageSystemUpdate;
13440            synchronized (mPackages) {
13441                if (res) {
13442                    if (!systemUpdate && mPackages.get(packageName) == null) {
13443                        removedForAllUsers = true;
13444                    }
13445                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13446                }
13447            }
13448            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13449                    + " removedForAllUsers=" + removedForAllUsers);
13450        }
13451
13452        if (res) {
13453            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13454
13455            // If the removed package was a system update, the old system package
13456            // was re-enabled; we need to broadcast this information
13457            if (systemUpdate) {
13458                Bundle extras = new Bundle(1);
13459                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13460                        ? info.removedAppId : info.uid);
13461                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13462
13463                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13464                        extras, 0, null, null, null);
13465                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13466                        extras, 0, null, null, null);
13467                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13468                        null, 0, packageName, null, null);
13469            }
13470        }
13471        // Force a gc here.
13472        Runtime.getRuntime().gc();
13473        // Delete the resources here after sending the broadcast to let
13474        // other processes clean up before deleting resources.
13475        if (info.args != null) {
13476            synchronized (mInstallLock) {
13477                info.args.doPostDeleteLI(true);
13478            }
13479        }
13480
13481        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13482    }
13483
13484    class PackageRemovedInfo {
13485        String removedPackage;
13486        int uid = -1;
13487        int removedAppId = -1;
13488        int[] removedUsers = null;
13489        boolean isRemovedPackageSystemUpdate = false;
13490        // Clean up resources deleted packages.
13491        InstallArgs args = null;
13492
13493        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13494            Bundle extras = new Bundle(1);
13495            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13496            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13497            if (replacing) {
13498                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13499            }
13500            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13501            if (removedPackage != null) {
13502                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13503                        extras, 0, null, null, removedUsers);
13504                if (fullRemove && !replacing) {
13505                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13506                            extras, 0, null, null, removedUsers);
13507                }
13508            }
13509            if (removedAppId >= 0) {
13510                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13511                        removedUsers);
13512            }
13513        }
13514    }
13515
13516    /*
13517     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13518     * flag is not set, the data directory is removed as well.
13519     * make sure this flag is set for partially installed apps. If not its meaningless to
13520     * delete a partially installed application.
13521     */
13522    private void removePackageDataLI(PackageSetting ps,
13523            int[] allUserHandles, boolean[] perUserInstalled,
13524            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13525        String packageName = ps.name;
13526        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13527        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13528        // Retrieve object to delete permissions for shared user later on
13529        final PackageSetting deletedPs;
13530        // reader
13531        synchronized (mPackages) {
13532            deletedPs = mSettings.mPackages.get(packageName);
13533            if (outInfo != null) {
13534                outInfo.removedPackage = packageName;
13535                outInfo.removedUsers = deletedPs != null
13536                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13537                        : null;
13538            }
13539        }
13540        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13541            removeDataDirsLI(ps.volumeUuid, packageName);
13542            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13543        }
13544        // writer
13545        synchronized (mPackages) {
13546            if (deletedPs != null) {
13547                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13548                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13549                    clearDefaultBrowserIfNeeded(packageName);
13550                    if (outInfo != null) {
13551                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13552                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13553                    }
13554                    updatePermissionsLPw(deletedPs.name, null, 0);
13555                    if (deletedPs.sharedUser != null) {
13556                        // Remove permissions associated with package. Since runtime
13557                        // permissions are per user we have to kill the removed package
13558                        // or packages running under the shared user of the removed
13559                        // package if revoking the permissions requested only by the removed
13560                        // package is successful and this causes a change in gids.
13561                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13562                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13563                                    userId);
13564                            if (userIdToKill == UserHandle.USER_ALL
13565                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13566                                // If gids changed for this user, kill all affected packages.
13567                                mHandler.post(new Runnable() {
13568                                    @Override
13569                                    public void run() {
13570                                        // This has to happen with no lock held.
13571                                        killApplication(deletedPs.name, deletedPs.appId,
13572                                                KILL_APP_REASON_GIDS_CHANGED);
13573                                    }
13574                                });
13575                                break;
13576                            }
13577                        }
13578                    }
13579                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13580                }
13581                // make sure to preserve per-user disabled state if this removal was just
13582                // a downgrade of a system app to the factory package
13583                if (allUserHandles != null && perUserInstalled != null) {
13584                    if (DEBUG_REMOVE) {
13585                        Slog.d(TAG, "Propagating install state across downgrade");
13586                    }
13587                    for (int i = 0; i < allUserHandles.length; i++) {
13588                        if (DEBUG_REMOVE) {
13589                            Slog.d(TAG, "    user " + allUserHandles[i]
13590                                    + " => " + perUserInstalled[i]);
13591                        }
13592                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13593                    }
13594                }
13595            }
13596            // can downgrade to reader
13597            if (writeSettings) {
13598                // Save settings now
13599                mSettings.writeLPr();
13600            }
13601        }
13602        if (outInfo != null) {
13603            // A user ID was deleted here. Go through all users and remove it
13604            // from KeyStore.
13605            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13606        }
13607    }
13608
13609    static boolean locationIsPrivileged(File path) {
13610        try {
13611            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13612                    .getCanonicalPath();
13613            return path.getCanonicalPath().startsWith(privilegedAppDir);
13614        } catch (IOException e) {
13615            Slog.e(TAG, "Unable to access code path " + path);
13616        }
13617        return false;
13618    }
13619
13620    /*
13621     * Tries to delete system package.
13622     */
13623    private boolean deleteSystemPackageLI(PackageSetting newPs,
13624            int[] allUserHandles, boolean[] perUserInstalled,
13625            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13626        final boolean applyUserRestrictions
13627                = (allUserHandles != null) && (perUserInstalled != null);
13628        PackageSetting disabledPs = null;
13629        // Confirm if the system package has been updated
13630        // An updated system app can be deleted. This will also have to restore
13631        // the system pkg from system partition
13632        // reader
13633        synchronized (mPackages) {
13634            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13635        }
13636        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13637                + " disabledPs=" + disabledPs);
13638        if (disabledPs == null) {
13639            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13640            return false;
13641        } else if (DEBUG_REMOVE) {
13642            Slog.d(TAG, "Deleting system pkg from data partition");
13643        }
13644        if (DEBUG_REMOVE) {
13645            if (applyUserRestrictions) {
13646                Slog.d(TAG, "Remembering install states:");
13647                for (int i = 0; i < allUserHandles.length; i++) {
13648                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13649                }
13650            }
13651        }
13652        // Delete the updated package
13653        outInfo.isRemovedPackageSystemUpdate = true;
13654        if (disabledPs.versionCode < newPs.versionCode) {
13655            // Delete data for downgrades
13656            flags &= ~PackageManager.DELETE_KEEP_DATA;
13657        } else {
13658            // Preserve data by setting flag
13659            flags |= PackageManager.DELETE_KEEP_DATA;
13660        }
13661        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13662                allUserHandles, perUserInstalled, outInfo, writeSettings);
13663        if (!ret) {
13664            return false;
13665        }
13666        // writer
13667        synchronized (mPackages) {
13668            // Reinstate the old system package
13669            mSettings.enableSystemPackageLPw(newPs.name);
13670            // Remove any native libraries from the upgraded package.
13671            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13672        }
13673        // Install the system package
13674        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13675        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13676        if (locationIsPrivileged(disabledPs.codePath)) {
13677            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13678        }
13679
13680        final PackageParser.Package newPkg;
13681        try {
13682            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13683        } catch (PackageManagerException e) {
13684            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13685            return false;
13686        }
13687
13688        // writer
13689        synchronized (mPackages) {
13690            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13691
13692            // Propagate the permissions state as we do not want to drop on the floor
13693            // runtime permissions. The update permissions method below will take
13694            // care of removing obsolete permissions and grant install permissions.
13695            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13696            updatePermissionsLPw(newPkg.packageName, newPkg,
13697                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13698
13699            if (applyUserRestrictions) {
13700                if (DEBUG_REMOVE) {
13701                    Slog.d(TAG, "Propagating install state across reinstall");
13702                }
13703                for (int i = 0; i < allUserHandles.length; i++) {
13704                    if (DEBUG_REMOVE) {
13705                        Slog.d(TAG, "    user " + allUserHandles[i]
13706                                + " => " + perUserInstalled[i]);
13707                    }
13708                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13709
13710                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13711                }
13712                // Regardless of writeSettings we need to ensure that this restriction
13713                // state propagation is persisted
13714                mSettings.writeAllUsersPackageRestrictionsLPr();
13715            }
13716            // can downgrade to reader here
13717            if (writeSettings) {
13718                mSettings.writeLPr();
13719            }
13720        }
13721        return true;
13722    }
13723
13724    private boolean deleteInstalledPackageLI(PackageSetting ps,
13725            boolean deleteCodeAndResources, int flags,
13726            int[] allUserHandles, boolean[] perUserInstalled,
13727            PackageRemovedInfo outInfo, boolean writeSettings) {
13728        if (outInfo != null) {
13729            outInfo.uid = ps.appId;
13730        }
13731
13732        // Delete package data from internal structures and also remove data if flag is set
13733        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13734
13735        // Delete application code and resources
13736        if (deleteCodeAndResources && (outInfo != null)) {
13737            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13738                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13739            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13740        }
13741        return true;
13742    }
13743
13744    @Override
13745    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13746            int userId) {
13747        mContext.enforceCallingOrSelfPermission(
13748                android.Manifest.permission.DELETE_PACKAGES, null);
13749        synchronized (mPackages) {
13750            PackageSetting ps = mSettings.mPackages.get(packageName);
13751            if (ps == null) {
13752                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13753                return false;
13754            }
13755            if (!ps.getInstalled(userId)) {
13756                // Can't block uninstall for an app that is not installed or enabled.
13757                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13758                return false;
13759            }
13760            ps.setBlockUninstall(blockUninstall, userId);
13761            mSettings.writePackageRestrictionsLPr(userId);
13762        }
13763        return true;
13764    }
13765
13766    @Override
13767    public boolean getBlockUninstallForUser(String packageName, int userId) {
13768        synchronized (mPackages) {
13769            PackageSetting ps = mSettings.mPackages.get(packageName);
13770            if (ps == null) {
13771                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13772                return false;
13773            }
13774            return ps.getBlockUninstall(userId);
13775        }
13776    }
13777
13778    @Override
13779    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13780        int callingUid = Binder.getCallingUid();
13781        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13782            throw new SecurityException(
13783                    "setRequiredForSystemUser can only be run by the system or root");
13784        }
13785        synchronized (mPackages) {
13786            PackageSetting ps = mSettings.mPackages.get(packageName);
13787            if (ps == null) {
13788                Log.w(TAG, "Package doesn't exist: " + packageName);
13789                return false;
13790            }
13791            if (systemUserApp) {
13792                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13793            } else {
13794                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13795            }
13796            mSettings.writeLPr();
13797        }
13798        return true;
13799    }
13800
13801    /*
13802     * This method handles package deletion in general
13803     */
13804    private boolean deletePackageLI(String packageName, UserHandle user,
13805            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13806            int flags, PackageRemovedInfo outInfo,
13807            boolean writeSettings) {
13808        if (packageName == null) {
13809            Slog.w(TAG, "Attempt to delete null packageName.");
13810            return false;
13811        }
13812        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13813        PackageSetting ps;
13814        boolean dataOnly = false;
13815        int removeUser = -1;
13816        int appId = -1;
13817        synchronized (mPackages) {
13818            ps = mSettings.mPackages.get(packageName);
13819            if (ps == null) {
13820                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13821                return false;
13822            }
13823            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13824                    && user.getIdentifier() != UserHandle.USER_ALL) {
13825                // The caller is asking that the package only be deleted for a single
13826                // user.  To do this, we just mark its uninstalled state and delete
13827                // its data.  If this is a system app, we only allow this to happen if
13828                // they have set the special DELETE_SYSTEM_APP which requests different
13829                // semantics than normal for uninstalling system apps.
13830                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13831                final int userId = user.getIdentifier();
13832                ps.setUserState(userId,
13833                        COMPONENT_ENABLED_STATE_DEFAULT,
13834                        false, //installed
13835                        true,  //stopped
13836                        true,  //notLaunched
13837                        false, //hidden
13838                        false, //suspended
13839                        null, null, null,
13840                        false, // blockUninstall
13841                        ps.readUserState(userId).domainVerificationStatus, 0);
13842                if (!isSystemApp(ps)) {
13843                    // Do not uninstall the APK if an app should be cached
13844                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13845                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13846                        // Other user still have this package installed, so all
13847                        // we need to do is clear this user's data and save that
13848                        // it is uninstalled.
13849                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13850                        removeUser = user.getIdentifier();
13851                        appId = ps.appId;
13852                        scheduleWritePackageRestrictionsLocked(removeUser);
13853                    } else {
13854                        // We need to set it back to 'installed' so the uninstall
13855                        // broadcasts will be sent correctly.
13856                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13857                        ps.setInstalled(true, user.getIdentifier());
13858                    }
13859                } else {
13860                    // This is a system app, so we assume that the
13861                    // other users still have this package installed, so all
13862                    // we need to do is clear this user's data and save that
13863                    // it is uninstalled.
13864                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13865                    removeUser = user.getIdentifier();
13866                    appId = ps.appId;
13867                    scheduleWritePackageRestrictionsLocked(removeUser);
13868                }
13869            }
13870        }
13871
13872        if (removeUser >= 0) {
13873            // From above, we determined that we are deleting this only
13874            // for a single user.  Continue the work here.
13875            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13876            if (outInfo != null) {
13877                outInfo.removedPackage = packageName;
13878                outInfo.removedAppId = appId;
13879                outInfo.removedUsers = new int[] {removeUser};
13880            }
13881            // TODO: triage flags as part of 26466827
13882            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13883            try {
13884                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13885            } catch (InstallerException e) {
13886                Slog.w(TAG, "Failed to delete app data", e);
13887            }
13888            removeKeystoreDataIfNeeded(removeUser, appId);
13889            schedulePackageCleaning(packageName, removeUser, false);
13890            synchronized (mPackages) {
13891                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13892                    scheduleWritePackageRestrictionsLocked(removeUser);
13893                }
13894                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13895            }
13896            return true;
13897        }
13898
13899        if (dataOnly) {
13900            // Delete application data first
13901            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13902            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13903            return true;
13904        }
13905
13906        boolean ret = false;
13907        if (isSystemApp(ps)) {
13908            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13909            // When an updated system application is deleted we delete the existing resources as well and
13910            // fall back to existing code in system partition
13911            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13912                    flags, outInfo, writeSettings);
13913        } else {
13914            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13915            // Kill application pre-emptively especially for apps on sd.
13916            killApplication(packageName, ps.appId, "uninstall pkg");
13917            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13918                    allUserHandles, perUserInstalled,
13919                    outInfo, writeSettings);
13920        }
13921
13922        return ret;
13923    }
13924
13925    private final static class ClearStorageConnection implements ServiceConnection {
13926        IMediaContainerService mContainerService;
13927
13928        @Override
13929        public void onServiceConnected(ComponentName name, IBinder service) {
13930            synchronized (this) {
13931                mContainerService = IMediaContainerService.Stub.asInterface(service);
13932                notifyAll();
13933            }
13934        }
13935
13936        @Override
13937        public void onServiceDisconnected(ComponentName name) {
13938        }
13939    }
13940
13941    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13942        final boolean mounted;
13943        if (Environment.isExternalStorageEmulated()) {
13944            mounted = true;
13945        } else {
13946            final String status = Environment.getExternalStorageState();
13947
13948            mounted = status.equals(Environment.MEDIA_MOUNTED)
13949                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13950        }
13951
13952        if (!mounted) {
13953            return;
13954        }
13955
13956        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13957        int[] users;
13958        if (userId == UserHandle.USER_ALL) {
13959            users = sUserManager.getUserIds();
13960        } else {
13961            users = new int[] { userId };
13962        }
13963        final ClearStorageConnection conn = new ClearStorageConnection();
13964        if (mContext.bindServiceAsUser(
13965                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13966            try {
13967                for (int curUser : users) {
13968                    long timeout = SystemClock.uptimeMillis() + 5000;
13969                    synchronized (conn) {
13970                        long now = SystemClock.uptimeMillis();
13971                        while (conn.mContainerService == null && now < timeout) {
13972                            try {
13973                                conn.wait(timeout - now);
13974                            } catch (InterruptedException e) {
13975                            }
13976                        }
13977                    }
13978                    if (conn.mContainerService == null) {
13979                        return;
13980                    }
13981
13982                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13983                    clearDirectory(conn.mContainerService,
13984                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13985                    if (allData) {
13986                        clearDirectory(conn.mContainerService,
13987                                userEnv.buildExternalStorageAppDataDirs(packageName));
13988                        clearDirectory(conn.mContainerService,
13989                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13990                    }
13991                }
13992            } finally {
13993                mContext.unbindService(conn);
13994            }
13995        }
13996    }
13997
13998    @Override
13999    public void clearApplicationUserData(final String packageName,
14000            final IPackageDataObserver observer, final int userId) {
14001        mContext.enforceCallingOrSelfPermission(
14002                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14003        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14004        // Queue up an async operation since the package deletion may take a little while.
14005        mHandler.post(new Runnable() {
14006            public void run() {
14007                mHandler.removeCallbacks(this);
14008                final boolean succeeded;
14009                synchronized (mInstallLock) {
14010                    succeeded = clearApplicationUserDataLI(packageName, userId);
14011                }
14012                clearExternalStorageDataSync(packageName, userId, true);
14013                if (succeeded) {
14014                    // invoke DeviceStorageMonitor's update method to clear any notifications
14015                    DeviceStorageMonitorInternal
14016                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14017                    if (dsm != null) {
14018                        dsm.checkMemory();
14019                    }
14020                }
14021                if(observer != null) {
14022                    try {
14023                        observer.onRemoveCompleted(packageName, succeeded);
14024                    } catch (RemoteException e) {
14025                        Log.i(TAG, "Observer no longer exists.");
14026                    }
14027                } //end if observer
14028            } //end run
14029        });
14030    }
14031
14032    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14033        if (packageName == null) {
14034            Slog.w(TAG, "Attempt to delete null packageName.");
14035            return false;
14036        }
14037
14038        // Try finding details about the requested package
14039        PackageParser.Package pkg;
14040        synchronized (mPackages) {
14041            pkg = mPackages.get(packageName);
14042            if (pkg == null) {
14043                final PackageSetting ps = mSettings.mPackages.get(packageName);
14044                if (ps != null) {
14045                    pkg = ps.pkg;
14046                }
14047            }
14048
14049            if (pkg == null) {
14050                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14051                return false;
14052            }
14053
14054            PackageSetting ps = (PackageSetting) pkg.mExtras;
14055            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14056        }
14057
14058        // Always delete data directories for package, even if we found no other
14059        // record of app. This helps users recover from UID mismatches without
14060        // resorting to a full data wipe.
14061        // TODO: triage flags as part of 26466827
14062        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14063        try {
14064            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14065        } catch (InstallerException e) {
14066            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14067            return false;
14068        }
14069
14070        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14071        removeKeystoreDataIfNeeded(userId, appId);
14072
14073        // Create a native library symlink only if we have native libraries
14074        // and if the native libraries are 32 bit libraries. We do not provide
14075        // this symlink for 64 bit libraries.
14076        if (pkg.applicationInfo.primaryCpuAbi != null &&
14077                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14078            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14079            try {
14080                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14081                        nativeLibPath, userId);
14082            } catch (InstallerException e) {
14083                Slog.w(TAG, "Failed linking native library dir", e);
14084                return false;
14085            }
14086        }
14087
14088        return true;
14089    }
14090
14091    /**
14092     * Reverts user permission state changes (permissions and flags) in
14093     * all packages for a given user.
14094     *
14095     * @param userId The device user for which to do a reset.
14096     */
14097    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14098        final int packageCount = mPackages.size();
14099        for (int i = 0; i < packageCount; i++) {
14100            PackageParser.Package pkg = mPackages.valueAt(i);
14101            PackageSetting ps = (PackageSetting) pkg.mExtras;
14102            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14103        }
14104    }
14105
14106    /**
14107     * Reverts user permission state changes (permissions and flags).
14108     *
14109     * @param ps The package for which to reset.
14110     * @param userId The device user for which to do a reset.
14111     */
14112    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14113            final PackageSetting ps, final int userId) {
14114        if (ps.pkg == null) {
14115            return;
14116        }
14117
14118        // These are flags that can change base on user actions.
14119        final int userSettableMask = FLAG_PERMISSION_USER_SET
14120                | FLAG_PERMISSION_USER_FIXED
14121                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14122                | FLAG_PERMISSION_REVIEW_REQUIRED;
14123
14124        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14125                | FLAG_PERMISSION_POLICY_FIXED;
14126
14127        boolean writeInstallPermissions = false;
14128        boolean writeRuntimePermissions = false;
14129
14130        final int permissionCount = ps.pkg.requestedPermissions.size();
14131        for (int i = 0; i < permissionCount; i++) {
14132            String permission = ps.pkg.requestedPermissions.get(i);
14133
14134            BasePermission bp = mSettings.mPermissions.get(permission);
14135            if (bp == null) {
14136                continue;
14137            }
14138
14139            // If shared user we just reset the state to which only this app contributed.
14140            if (ps.sharedUser != null) {
14141                boolean used = false;
14142                final int packageCount = ps.sharedUser.packages.size();
14143                for (int j = 0; j < packageCount; j++) {
14144                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14145                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14146                            && pkg.pkg.requestedPermissions.contains(permission)) {
14147                        used = true;
14148                        break;
14149                    }
14150                }
14151                if (used) {
14152                    continue;
14153                }
14154            }
14155
14156            PermissionsState permissionsState = ps.getPermissionsState();
14157
14158            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14159
14160            // Always clear the user settable flags.
14161            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14162                    bp.name) != null;
14163            // If permission review is enabled and this is a legacy app, mark the
14164            // permission as requiring a review as this is the initial state.
14165            int flags = 0;
14166            if (Build.PERMISSIONS_REVIEW_REQUIRED
14167                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14168                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14169            }
14170            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14171                if (hasInstallState) {
14172                    writeInstallPermissions = true;
14173                } else {
14174                    writeRuntimePermissions = true;
14175                }
14176            }
14177
14178            // Below is only runtime permission handling.
14179            if (!bp.isRuntime()) {
14180                continue;
14181            }
14182
14183            // Never clobber system or policy.
14184            if ((oldFlags & policyOrSystemFlags) != 0) {
14185                continue;
14186            }
14187
14188            // If this permission was granted by default, make sure it is.
14189            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14190                if (permissionsState.grantRuntimePermission(bp, userId)
14191                        != PERMISSION_OPERATION_FAILURE) {
14192                    writeRuntimePermissions = true;
14193                }
14194            // If permission review is enabled the permissions for a legacy apps
14195            // are represented as constantly granted runtime ones, so don't revoke.
14196            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14197                // Otherwise, reset the permission.
14198                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14199                switch (revokeResult) {
14200                    case PERMISSION_OPERATION_SUCCESS: {
14201                        writeRuntimePermissions = true;
14202                    } break;
14203
14204                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14205                        writeRuntimePermissions = true;
14206                        final int appId = ps.appId;
14207                        mHandler.post(new Runnable() {
14208                            @Override
14209                            public void run() {
14210                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14211                            }
14212                        });
14213                    } break;
14214                }
14215            }
14216        }
14217
14218        // Synchronously write as we are taking permissions away.
14219        if (writeRuntimePermissions) {
14220            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14221        }
14222
14223        // Synchronously write as we are taking permissions away.
14224        if (writeInstallPermissions) {
14225            mSettings.writeLPr();
14226        }
14227    }
14228
14229    /**
14230     * Remove entries from the keystore daemon. Will only remove it if the
14231     * {@code appId} is valid.
14232     */
14233    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14234        if (appId < 0) {
14235            return;
14236        }
14237
14238        final KeyStore keyStore = KeyStore.getInstance();
14239        if (keyStore != null) {
14240            if (userId == UserHandle.USER_ALL) {
14241                for (final int individual : sUserManager.getUserIds()) {
14242                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14243                }
14244            } else {
14245                keyStore.clearUid(UserHandle.getUid(userId, appId));
14246            }
14247        } else {
14248            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14249        }
14250    }
14251
14252    @Override
14253    public void deleteApplicationCacheFiles(final String packageName,
14254            final IPackageDataObserver observer) {
14255        mContext.enforceCallingOrSelfPermission(
14256                android.Manifest.permission.DELETE_CACHE_FILES, null);
14257        // Queue up an async operation since the package deletion may take a little while.
14258        final int userId = UserHandle.getCallingUserId();
14259        mHandler.post(new Runnable() {
14260            public void run() {
14261                mHandler.removeCallbacks(this);
14262                final boolean succeded;
14263                synchronized (mInstallLock) {
14264                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14265                }
14266                clearExternalStorageDataSync(packageName, userId, false);
14267                if (observer != null) {
14268                    try {
14269                        observer.onRemoveCompleted(packageName, succeded);
14270                    } catch (RemoteException e) {
14271                        Log.i(TAG, "Observer no longer exists.");
14272                    }
14273                } //end if observer
14274            } //end run
14275        });
14276    }
14277
14278    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14279        if (packageName == null) {
14280            Slog.w(TAG, "Attempt to delete null packageName.");
14281            return false;
14282        }
14283        PackageParser.Package p;
14284        synchronized (mPackages) {
14285            p = mPackages.get(packageName);
14286        }
14287        if (p == null) {
14288            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14289            return false;
14290        }
14291        final ApplicationInfo applicationInfo = p.applicationInfo;
14292        if (applicationInfo == null) {
14293            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14294            return false;
14295        }
14296        // TODO: triage flags as part of 26466827
14297        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14298        try {
14299            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14300                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14301        } catch (InstallerException e) {
14302            Slog.w(TAG, "Couldn't remove cache files for package "
14303                    + packageName + " u" + userId, e);
14304            return false;
14305        }
14306        return true;
14307    }
14308
14309    @Override
14310    public void getPackageSizeInfo(final String packageName, int userHandle,
14311            final IPackageStatsObserver observer) {
14312        mContext.enforceCallingOrSelfPermission(
14313                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14314        if (packageName == null) {
14315            throw new IllegalArgumentException("Attempt to get size of null packageName");
14316        }
14317
14318        PackageStats stats = new PackageStats(packageName, userHandle);
14319
14320        /*
14321         * Queue up an async operation since the package measurement may take a
14322         * little while.
14323         */
14324        Message msg = mHandler.obtainMessage(INIT_COPY);
14325        msg.obj = new MeasureParams(stats, observer);
14326        mHandler.sendMessage(msg);
14327    }
14328
14329    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14330            PackageStats pStats) {
14331        if (packageName == null) {
14332            Slog.w(TAG, "Attempt to get size of null packageName.");
14333            return false;
14334        }
14335        PackageParser.Package p;
14336        boolean dataOnly = false;
14337        String libDirRoot = null;
14338        String asecPath = null;
14339        PackageSetting ps = null;
14340        synchronized (mPackages) {
14341            p = mPackages.get(packageName);
14342            ps = mSettings.mPackages.get(packageName);
14343            if(p == null) {
14344                dataOnly = true;
14345                if((ps == null) || (ps.pkg == null)) {
14346                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14347                    return false;
14348                }
14349                p = ps.pkg;
14350            }
14351            if (ps != null) {
14352                libDirRoot = ps.legacyNativeLibraryPathString;
14353            }
14354            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14355                final long token = Binder.clearCallingIdentity();
14356                try {
14357                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14358                    if (secureContainerId != null) {
14359                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14360                    }
14361                } finally {
14362                    Binder.restoreCallingIdentity(token);
14363                }
14364            }
14365        }
14366        String publicSrcDir = null;
14367        if(!dataOnly) {
14368            final ApplicationInfo applicationInfo = p.applicationInfo;
14369            if (applicationInfo == null) {
14370                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14371                return false;
14372            }
14373            if (p.isForwardLocked()) {
14374                publicSrcDir = applicationInfo.getBaseResourcePath();
14375            }
14376        }
14377        // TODO: extend to measure size of split APKs
14378        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14379        // not just the first level.
14380        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14381        // just the primary.
14382        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14383
14384        String apkPath;
14385        File packageDir = new File(p.codePath);
14386
14387        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14388            apkPath = packageDir.getAbsolutePath();
14389            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14390            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14391                libDirRoot = null;
14392            }
14393        } else {
14394            apkPath = p.baseCodePath;
14395        }
14396
14397        // TODO: triage flags as part of 26466827
14398        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14399        try {
14400            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14401                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14402        } catch (InstallerException e) {
14403            return false;
14404        }
14405
14406        // Fix-up for forward-locked applications in ASEC containers.
14407        if (!isExternal(p)) {
14408            pStats.codeSize += pStats.externalCodeSize;
14409            pStats.externalCodeSize = 0L;
14410        }
14411
14412        return true;
14413    }
14414
14415
14416    @Override
14417    public void addPackageToPreferred(String packageName) {
14418        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14419    }
14420
14421    @Override
14422    public void removePackageFromPreferred(String packageName) {
14423        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14424    }
14425
14426    @Override
14427    public List<PackageInfo> getPreferredPackages(int flags) {
14428        return new ArrayList<PackageInfo>();
14429    }
14430
14431    private int getUidTargetSdkVersionLockedLPr(int uid) {
14432        Object obj = mSettings.getUserIdLPr(uid);
14433        if (obj instanceof SharedUserSetting) {
14434            final SharedUserSetting sus = (SharedUserSetting) obj;
14435            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14436            final Iterator<PackageSetting> it = sus.packages.iterator();
14437            while (it.hasNext()) {
14438                final PackageSetting ps = it.next();
14439                if (ps.pkg != null) {
14440                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14441                    if (v < vers) vers = v;
14442                }
14443            }
14444            return vers;
14445        } else if (obj instanceof PackageSetting) {
14446            final PackageSetting ps = (PackageSetting) obj;
14447            if (ps.pkg != null) {
14448                return ps.pkg.applicationInfo.targetSdkVersion;
14449            }
14450        }
14451        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14452    }
14453
14454    @Override
14455    public void addPreferredActivity(IntentFilter filter, int match,
14456            ComponentName[] set, ComponentName activity, int userId) {
14457        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14458                "Adding preferred");
14459    }
14460
14461    private void addPreferredActivityInternal(IntentFilter filter, int match,
14462            ComponentName[] set, ComponentName activity, boolean always, int userId,
14463            String opname) {
14464        // writer
14465        int callingUid = Binder.getCallingUid();
14466        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14467        if (filter.countActions() == 0) {
14468            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14469            return;
14470        }
14471        synchronized (mPackages) {
14472            if (mContext.checkCallingOrSelfPermission(
14473                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14474                    != PackageManager.PERMISSION_GRANTED) {
14475                if (getUidTargetSdkVersionLockedLPr(callingUid)
14476                        < Build.VERSION_CODES.FROYO) {
14477                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14478                            + callingUid);
14479                    return;
14480                }
14481                mContext.enforceCallingOrSelfPermission(
14482                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14483            }
14484
14485            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14486            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14487                    + userId + ":");
14488            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14489            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14490            scheduleWritePackageRestrictionsLocked(userId);
14491        }
14492    }
14493
14494    @Override
14495    public void replacePreferredActivity(IntentFilter filter, int match,
14496            ComponentName[] set, ComponentName activity, int userId) {
14497        if (filter.countActions() != 1) {
14498            throw new IllegalArgumentException(
14499                    "replacePreferredActivity expects filter to have only 1 action.");
14500        }
14501        if (filter.countDataAuthorities() != 0
14502                || filter.countDataPaths() != 0
14503                || filter.countDataSchemes() > 1
14504                || filter.countDataTypes() != 0) {
14505            throw new IllegalArgumentException(
14506                    "replacePreferredActivity expects filter to have no data authorities, " +
14507                    "paths, or types; and at most one scheme.");
14508        }
14509
14510        final int callingUid = Binder.getCallingUid();
14511        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14512        synchronized (mPackages) {
14513            if (mContext.checkCallingOrSelfPermission(
14514                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14515                    != PackageManager.PERMISSION_GRANTED) {
14516                if (getUidTargetSdkVersionLockedLPr(callingUid)
14517                        < Build.VERSION_CODES.FROYO) {
14518                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14519                            + Binder.getCallingUid());
14520                    return;
14521                }
14522                mContext.enforceCallingOrSelfPermission(
14523                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14524            }
14525
14526            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14527            if (pir != null) {
14528                // Get all of the existing entries that exactly match this filter.
14529                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14530                if (existing != null && existing.size() == 1) {
14531                    PreferredActivity cur = existing.get(0);
14532                    if (DEBUG_PREFERRED) {
14533                        Slog.i(TAG, "Checking replace of preferred:");
14534                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14535                        if (!cur.mPref.mAlways) {
14536                            Slog.i(TAG, "  -- CUR; not mAlways!");
14537                        } else {
14538                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14539                            Slog.i(TAG, "  -- CUR: mSet="
14540                                    + Arrays.toString(cur.mPref.mSetComponents));
14541                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14542                            Slog.i(TAG, "  -- NEW: mMatch="
14543                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14544                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14545                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14546                        }
14547                    }
14548                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14549                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14550                            && cur.mPref.sameSet(set)) {
14551                        // Setting the preferred activity to what it happens to be already
14552                        if (DEBUG_PREFERRED) {
14553                            Slog.i(TAG, "Replacing with same preferred activity "
14554                                    + cur.mPref.mShortComponent + " for user "
14555                                    + userId + ":");
14556                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14557                        }
14558                        return;
14559                    }
14560                }
14561
14562                if (existing != null) {
14563                    if (DEBUG_PREFERRED) {
14564                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14565                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14566                    }
14567                    for (int i = 0; i < existing.size(); i++) {
14568                        PreferredActivity pa = existing.get(i);
14569                        if (DEBUG_PREFERRED) {
14570                            Slog.i(TAG, "Removing existing preferred activity "
14571                                    + pa.mPref.mComponent + ":");
14572                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14573                        }
14574                        pir.removeFilter(pa);
14575                    }
14576                }
14577            }
14578            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14579                    "Replacing preferred");
14580        }
14581    }
14582
14583    @Override
14584    public void clearPackagePreferredActivities(String packageName) {
14585        final int uid = Binder.getCallingUid();
14586        // writer
14587        synchronized (mPackages) {
14588            PackageParser.Package pkg = mPackages.get(packageName);
14589            if (pkg == null || pkg.applicationInfo.uid != uid) {
14590                if (mContext.checkCallingOrSelfPermission(
14591                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14592                        != PackageManager.PERMISSION_GRANTED) {
14593                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14594                            < Build.VERSION_CODES.FROYO) {
14595                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14596                                + Binder.getCallingUid());
14597                        return;
14598                    }
14599                    mContext.enforceCallingOrSelfPermission(
14600                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14601                }
14602            }
14603
14604            int user = UserHandle.getCallingUserId();
14605            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14606                scheduleWritePackageRestrictionsLocked(user);
14607            }
14608        }
14609    }
14610
14611    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14612    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14613        ArrayList<PreferredActivity> removed = null;
14614        boolean changed = false;
14615        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14616            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14617            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14618            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14619                continue;
14620            }
14621            Iterator<PreferredActivity> it = pir.filterIterator();
14622            while (it.hasNext()) {
14623                PreferredActivity pa = it.next();
14624                // Mark entry for removal only if it matches the package name
14625                // and the entry is of type "always".
14626                if (packageName == null ||
14627                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14628                                && pa.mPref.mAlways)) {
14629                    if (removed == null) {
14630                        removed = new ArrayList<PreferredActivity>();
14631                    }
14632                    removed.add(pa);
14633                }
14634            }
14635            if (removed != null) {
14636                for (int j=0; j<removed.size(); j++) {
14637                    PreferredActivity pa = removed.get(j);
14638                    pir.removeFilter(pa);
14639                }
14640                changed = true;
14641            }
14642        }
14643        return changed;
14644    }
14645
14646    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14647    private void clearIntentFilterVerificationsLPw(int userId) {
14648        final int packageCount = mPackages.size();
14649        for (int i = 0; i < packageCount; i++) {
14650            PackageParser.Package pkg = mPackages.valueAt(i);
14651            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14652        }
14653    }
14654
14655    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14656    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14657        if (userId == UserHandle.USER_ALL) {
14658            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14659                    sUserManager.getUserIds())) {
14660                for (int oneUserId : sUserManager.getUserIds()) {
14661                    scheduleWritePackageRestrictionsLocked(oneUserId);
14662                }
14663            }
14664        } else {
14665            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14666                scheduleWritePackageRestrictionsLocked(userId);
14667            }
14668        }
14669    }
14670
14671    void clearDefaultBrowserIfNeeded(String packageName) {
14672        for (int oneUserId : sUserManager.getUserIds()) {
14673            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14674            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14675            if (packageName.equals(defaultBrowserPackageName)) {
14676                setDefaultBrowserPackageName(null, oneUserId);
14677            }
14678        }
14679    }
14680
14681    @Override
14682    public void resetApplicationPreferences(int userId) {
14683        mContext.enforceCallingOrSelfPermission(
14684                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14685        // writer
14686        synchronized (mPackages) {
14687            final long identity = Binder.clearCallingIdentity();
14688            try {
14689                clearPackagePreferredActivitiesLPw(null, userId);
14690                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14691                // TODO: We have to reset the default SMS and Phone. This requires
14692                // significant refactoring to keep all default apps in the package
14693                // manager (cleaner but more work) or have the services provide
14694                // callbacks to the package manager to request a default app reset.
14695                applyFactoryDefaultBrowserLPw(userId);
14696                clearIntentFilterVerificationsLPw(userId);
14697                primeDomainVerificationsLPw(userId);
14698                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14699                scheduleWritePackageRestrictionsLocked(userId);
14700            } finally {
14701                Binder.restoreCallingIdentity(identity);
14702            }
14703        }
14704    }
14705
14706    @Override
14707    public int getPreferredActivities(List<IntentFilter> outFilters,
14708            List<ComponentName> outActivities, String packageName) {
14709
14710        int num = 0;
14711        final int userId = UserHandle.getCallingUserId();
14712        // reader
14713        synchronized (mPackages) {
14714            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14715            if (pir != null) {
14716                final Iterator<PreferredActivity> it = pir.filterIterator();
14717                while (it.hasNext()) {
14718                    final PreferredActivity pa = it.next();
14719                    if (packageName == null
14720                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14721                                    && pa.mPref.mAlways)) {
14722                        if (outFilters != null) {
14723                            outFilters.add(new IntentFilter(pa));
14724                        }
14725                        if (outActivities != null) {
14726                            outActivities.add(pa.mPref.mComponent);
14727                        }
14728                    }
14729                }
14730            }
14731        }
14732
14733        return num;
14734    }
14735
14736    @Override
14737    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14738            int userId) {
14739        int callingUid = Binder.getCallingUid();
14740        if (callingUid != Process.SYSTEM_UID) {
14741            throw new SecurityException(
14742                    "addPersistentPreferredActivity can only be run by the system");
14743        }
14744        if (filter.countActions() == 0) {
14745            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14746            return;
14747        }
14748        synchronized (mPackages) {
14749            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14750                    ":");
14751            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14752            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14753                    new PersistentPreferredActivity(filter, activity));
14754            scheduleWritePackageRestrictionsLocked(userId);
14755        }
14756    }
14757
14758    @Override
14759    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14760        int callingUid = Binder.getCallingUid();
14761        if (callingUid != Process.SYSTEM_UID) {
14762            throw new SecurityException(
14763                    "clearPackagePersistentPreferredActivities can only be run by the system");
14764        }
14765        ArrayList<PersistentPreferredActivity> removed = null;
14766        boolean changed = false;
14767        synchronized (mPackages) {
14768            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14769                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14770                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14771                        .valueAt(i);
14772                if (userId != thisUserId) {
14773                    continue;
14774                }
14775                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14776                while (it.hasNext()) {
14777                    PersistentPreferredActivity ppa = it.next();
14778                    // Mark entry for removal only if it matches the package name.
14779                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14780                        if (removed == null) {
14781                            removed = new ArrayList<PersistentPreferredActivity>();
14782                        }
14783                        removed.add(ppa);
14784                    }
14785                }
14786                if (removed != null) {
14787                    for (int j=0; j<removed.size(); j++) {
14788                        PersistentPreferredActivity ppa = removed.get(j);
14789                        ppir.removeFilter(ppa);
14790                    }
14791                    changed = true;
14792                }
14793            }
14794
14795            if (changed) {
14796                scheduleWritePackageRestrictionsLocked(userId);
14797            }
14798        }
14799    }
14800
14801    /**
14802     * Common machinery for picking apart a restored XML blob and passing
14803     * it to a caller-supplied functor to be applied to the running system.
14804     */
14805    private void restoreFromXml(XmlPullParser parser, int userId,
14806            String expectedStartTag, BlobXmlRestorer functor)
14807            throws IOException, XmlPullParserException {
14808        int type;
14809        while ((type = parser.next()) != XmlPullParser.START_TAG
14810                && type != XmlPullParser.END_DOCUMENT) {
14811        }
14812        if (type != XmlPullParser.START_TAG) {
14813            // oops didn't find a start tag?!
14814            if (DEBUG_BACKUP) {
14815                Slog.e(TAG, "Didn't find start tag during restore");
14816            }
14817            return;
14818        }
14819
14820        // this is supposed to be TAG_PREFERRED_BACKUP
14821        if (!expectedStartTag.equals(parser.getName())) {
14822            if (DEBUG_BACKUP) {
14823                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14824            }
14825            return;
14826        }
14827
14828        // skip interfering stuff, then we're aligned with the backing implementation
14829        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14830        functor.apply(parser, userId);
14831    }
14832
14833    private interface BlobXmlRestorer {
14834        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14835    }
14836
14837    /**
14838     * Non-Binder method, support for the backup/restore mechanism: write the
14839     * full set of preferred activities in its canonical XML format.  Returns the
14840     * XML output as a byte array, or null if there is none.
14841     */
14842    @Override
14843    public byte[] getPreferredActivityBackup(int userId) {
14844        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14845            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14846        }
14847
14848        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14849        try {
14850            final XmlSerializer serializer = new FastXmlSerializer();
14851            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14852            serializer.startDocument(null, true);
14853            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14854
14855            synchronized (mPackages) {
14856                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14857            }
14858
14859            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14860            serializer.endDocument();
14861            serializer.flush();
14862        } catch (Exception e) {
14863            if (DEBUG_BACKUP) {
14864                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14865            }
14866            return null;
14867        }
14868
14869        return dataStream.toByteArray();
14870    }
14871
14872    @Override
14873    public void restorePreferredActivities(byte[] backup, int userId) {
14874        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14875            throw new SecurityException("Only the system may call restorePreferredActivities()");
14876        }
14877
14878        try {
14879            final XmlPullParser parser = Xml.newPullParser();
14880            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14881            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14882                    new BlobXmlRestorer() {
14883                        @Override
14884                        public void apply(XmlPullParser parser, int userId)
14885                                throws XmlPullParserException, IOException {
14886                            synchronized (mPackages) {
14887                                mSettings.readPreferredActivitiesLPw(parser, userId);
14888                            }
14889                        }
14890                    } );
14891        } catch (Exception e) {
14892            if (DEBUG_BACKUP) {
14893                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14894            }
14895        }
14896    }
14897
14898    /**
14899     * Non-Binder method, support for the backup/restore mechanism: write the
14900     * default browser (etc) settings in its canonical XML format.  Returns the default
14901     * browser XML representation as a byte array, or null if there is none.
14902     */
14903    @Override
14904    public byte[] getDefaultAppsBackup(int userId) {
14905        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14906            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14907        }
14908
14909        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14910        try {
14911            final XmlSerializer serializer = new FastXmlSerializer();
14912            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14913            serializer.startDocument(null, true);
14914            serializer.startTag(null, TAG_DEFAULT_APPS);
14915
14916            synchronized (mPackages) {
14917                mSettings.writeDefaultAppsLPr(serializer, userId);
14918            }
14919
14920            serializer.endTag(null, TAG_DEFAULT_APPS);
14921            serializer.endDocument();
14922            serializer.flush();
14923        } catch (Exception e) {
14924            if (DEBUG_BACKUP) {
14925                Slog.e(TAG, "Unable to write default apps for backup", e);
14926            }
14927            return null;
14928        }
14929
14930        return dataStream.toByteArray();
14931    }
14932
14933    @Override
14934    public void restoreDefaultApps(byte[] backup, int userId) {
14935        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14936            throw new SecurityException("Only the system may call restoreDefaultApps()");
14937        }
14938
14939        try {
14940            final XmlPullParser parser = Xml.newPullParser();
14941            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14942            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14943                    new BlobXmlRestorer() {
14944                        @Override
14945                        public void apply(XmlPullParser parser, int userId)
14946                                throws XmlPullParserException, IOException {
14947                            synchronized (mPackages) {
14948                                mSettings.readDefaultAppsLPw(parser, userId);
14949                            }
14950                        }
14951                    } );
14952        } catch (Exception e) {
14953            if (DEBUG_BACKUP) {
14954                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14955            }
14956        }
14957    }
14958
14959    @Override
14960    public byte[] getIntentFilterVerificationBackup(int userId) {
14961        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14962            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14963        }
14964
14965        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14966        try {
14967            final XmlSerializer serializer = new FastXmlSerializer();
14968            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14969            serializer.startDocument(null, true);
14970            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14971
14972            synchronized (mPackages) {
14973                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14974            }
14975
14976            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14977            serializer.endDocument();
14978            serializer.flush();
14979        } catch (Exception e) {
14980            if (DEBUG_BACKUP) {
14981                Slog.e(TAG, "Unable to write default apps for backup", e);
14982            }
14983            return null;
14984        }
14985
14986        return dataStream.toByteArray();
14987    }
14988
14989    @Override
14990    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14992            throw new SecurityException("Only the system may call restorePreferredActivities()");
14993        }
14994
14995        try {
14996            final XmlPullParser parser = Xml.newPullParser();
14997            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14998            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14999                    new BlobXmlRestorer() {
15000                        @Override
15001                        public void apply(XmlPullParser parser, int userId)
15002                                throws XmlPullParserException, IOException {
15003                            synchronized (mPackages) {
15004                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15005                                mSettings.writeLPr();
15006                            }
15007                        }
15008                    } );
15009        } catch (Exception e) {
15010            if (DEBUG_BACKUP) {
15011                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15012            }
15013        }
15014    }
15015
15016    @Override
15017    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15018            int sourceUserId, int targetUserId, int flags) {
15019        mContext.enforceCallingOrSelfPermission(
15020                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15021        int callingUid = Binder.getCallingUid();
15022        enforceOwnerRights(ownerPackage, callingUid);
15023        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15024        if (intentFilter.countActions() == 0) {
15025            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15026            return;
15027        }
15028        synchronized (mPackages) {
15029            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15030                    ownerPackage, targetUserId, flags);
15031            CrossProfileIntentResolver resolver =
15032                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15033            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15034            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15035            if (existing != null) {
15036                int size = existing.size();
15037                for (int i = 0; i < size; i++) {
15038                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15039                        return;
15040                    }
15041                }
15042            }
15043            resolver.addFilter(newFilter);
15044            scheduleWritePackageRestrictionsLocked(sourceUserId);
15045        }
15046    }
15047
15048    @Override
15049    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15050        mContext.enforceCallingOrSelfPermission(
15051                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15052        int callingUid = Binder.getCallingUid();
15053        enforceOwnerRights(ownerPackage, callingUid);
15054        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15055        synchronized (mPackages) {
15056            CrossProfileIntentResolver resolver =
15057                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15058            ArraySet<CrossProfileIntentFilter> set =
15059                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15060            for (CrossProfileIntentFilter filter : set) {
15061                if (filter.getOwnerPackage().equals(ownerPackage)) {
15062                    resolver.removeFilter(filter);
15063                }
15064            }
15065            scheduleWritePackageRestrictionsLocked(sourceUserId);
15066        }
15067    }
15068
15069    // Enforcing that callingUid is owning pkg on userId
15070    private void enforceOwnerRights(String pkg, int callingUid) {
15071        // The system owns everything.
15072        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15073            return;
15074        }
15075        int callingUserId = UserHandle.getUserId(callingUid);
15076        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15077        if (pi == null) {
15078            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15079                    + callingUserId);
15080        }
15081        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15082            throw new SecurityException("Calling uid " + callingUid
15083                    + " does not own package " + pkg);
15084        }
15085    }
15086
15087    @Override
15088    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15089        Intent intent = new Intent(Intent.ACTION_MAIN);
15090        intent.addCategory(Intent.CATEGORY_HOME);
15091
15092        final int callingUserId = UserHandle.getCallingUserId();
15093        List<ResolveInfo> list = queryIntentActivities(intent, null,
15094                PackageManager.GET_META_DATA, callingUserId);
15095        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15096                true, false, false, callingUserId);
15097
15098        allHomeCandidates.clear();
15099        if (list != null) {
15100            for (ResolveInfo ri : list) {
15101                allHomeCandidates.add(ri);
15102            }
15103        }
15104        return (preferred == null || preferred.activityInfo == null)
15105                ? null
15106                : new ComponentName(preferred.activityInfo.packageName,
15107                        preferred.activityInfo.name);
15108    }
15109
15110    @Override
15111    public void setApplicationEnabledSetting(String appPackageName,
15112            int newState, int flags, int userId, String callingPackage) {
15113        if (!sUserManager.exists(userId)) return;
15114        if (callingPackage == null) {
15115            callingPackage = Integer.toString(Binder.getCallingUid());
15116        }
15117        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15118    }
15119
15120    @Override
15121    public void setComponentEnabledSetting(ComponentName componentName,
15122            int newState, int flags, int userId) {
15123        if (!sUserManager.exists(userId)) return;
15124        setEnabledSetting(componentName.getPackageName(),
15125                componentName.getClassName(), newState, flags, userId, null);
15126    }
15127
15128    private void setEnabledSetting(final String packageName, String className, int newState,
15129            final int flags, int userId, String callingPackage) {
15130        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15131              || newState == COMPONENT_ENABLED_STATE_ENABLED
15132              || newState == COMPONENT_ENABLED_STATE_DISABLED
15133              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15134              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15135            throw new IllegalArgumentException("Invalid new component state: "
15136                    + newState);
15137        }
15138        PackageSetting pkgSetting;
15139        final int uid = Binder.getCallingUid();
15140        final int permission = mContext.checkCallingOrSelfPermission(
15141                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15142        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15143        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15144        boolean sendNow = false;
15145        boolean isApp = (className == null);
15146        String componentName = isApp ? packageName : className;
15147        int packageUid = -1;
15148        ArrayList<String> components;
15149
15150        // writer
15151        synchronized (mPackages) {
15152            pkgSetting = mSettings.mPackages.get(packageName);
15153            if (pkgSetting == null) {
15154                if (className == null) {
15155                    throw new IllegalArgumentException("Unknown package: " + packageName);
15156                }
15157                throw new IllegalArgumentException(
15158                        "Unknown component: " + packageName + "/" + className);
15159            }
15160            // Allow root and verify that userId is not being specified by a different user
15161            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15162                throw new SecurityException(
15163                        "Permission Denial: attempt to change component state from pid="
15164                        + Binder.getCallingPid()
15165                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15166            }
15167            if (className == null) {
15168                // We're dealing with an application/package level state change
15169                if (pkgSetting.getEnabled(userId) == newState) {
15170                    // Nothing to do
15171                    return;
15172                }
15173                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15174                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15175                    // Don't care about who enables an app.
15176                    callingPackage = null;
15177                }
15178                pkgSetting.setEnabled(newState, userId, callingPackage);
15179                // pkgSetting.pkg.mSetEnabled = newState;
15180            } else {
15181                // We're dealing with a component level state change
15182                // First, verify that this is a valid class name.
15183                PackageParser.Package pkg = pkgSetting.pkg;
15184                if (pkg == null || !pkg.hasComponentClassName(className)) {
15185                    if (pkg != null &&
15186                            pkg.applicationInfo.targetSdkVersion >=
15187                                    Build.VERSION_CODES.JELLY_BEAN) {
15188                        throw new IllegalArgumentException("Component class " + className
15189                                + " does not exist in " + packageName);
15190                    } else {
15191                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15192                                + className + " does not exist in " + packageName);
15193                    }
15194                }
15195                switch (newState) {
15196                case COMPONENT_ENABLED_STATE_ENABLED:
15197                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15198                        return;
15199                    }
15200                    break;
15201                case COMPONENT_ENABLED_STATE_DISABLED:
15202                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15203                        return;
15204                    }
15205                    break;
15206                case COMPONENT_ENABLED_STATE_DEFAULT:
15207                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15208                        return;
15209                    }
15210                    break;
15211                default:
15212                    Slog.e(TAG, "Invalid new component state: " + newState);
15213                    return;
15214                }
15215            }
15216            scheduleWritePackageRestrictionsLocked(userId);
15217            components = mPendingBroadcasts.get(userId, packageName);
15218            final boolean newPackage = components == null;
15219            if (newPackage) {
15220                components = new ArrayList<String>();
15221            }
15222            if (!components.contains(componentName)) {
15223                components.add(componentName);
15224            }
15225            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15226                sendNow = true;
15227                // Purge entry from pending broadcast list if another one exists already
15228                // since we are sending one right away.
15229                mPendingBroadcasts.remove(userId, packageName);
15230            } else {
15231                if (newPackage) {
15232                    mPendingBroadcasts.put(userId, packageName, components);
15233                }
15234                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15235                    // Schedule a message
15236                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15237                }
15238            }
15239        }
15240
15241        long callingId = Binder.clearCallingIdentity();
15242        try {
15243            if (sendNow) {
15244                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15245                sendPackageChangedBroadcast(packageName,
15246                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15247            }
15248        } finally {
15249            Binder.restoreCallingIdentity(callingId);
15250        }
15251    }
15252
15253    private void sendPackageChangedBroadcast(String packageName,
15254            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15255        if (DEBUG_INSTALL)
15256            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15257                    + componentNames);
15258        Bundle extras = new Bundle(4);
15259        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15260        String nameList[] = new String[componentNames.size()];
15261        componentNames.toArray(nameList);
15262        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15263        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15264        extras.putInt(Intent.EXTRA_UID, packageUid);
15265        // If this is not reporting a change of the overall package, then only send it
15266        // to registered receivers.  We don't want to launch a swath of apps for every
15267        // little component state change.
15268        final int flags = !componentNames.contains(packageName)
15269                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15270        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15271                new int[] {UserHandle.getUserId(packageUid)});
15272    }
15273
15274    @Override
15275    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15276        if (!sUserManager.exists(userId)) return;
15277        final int uid = Binder.getCallingUid();
15278        final int permission = mContext.checkCallingOrSelfPermission(
15279                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15280        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15281        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15282        // writer
15283        synchronized (mPackages) {
15284            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15285                    allowedByPermission, uid, userId)) {
15286                scheduleWritePackageRestrictionsLocked(userId);
15287            }
15288        }
15289    }
15290
15291    @Override
15292    public String getInstallerPackageName(String packageName) {
15293        // reader
15294        synchronized (mPackages) {
15295            return mSettings.getInstallerPackageNameLPr(packageName);
15296        }
15297    }
15298
15299    @Override
15300    public int getApplicationEnabledSetting(String packageName, int userId) {
15301        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15302        int uid = Binder.getCallingUid();
15303        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15304        // reader
15305        synchronized (mPackages) {
15306            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15307        }
15308    }
15309
15310    @Override
15311    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15312        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15313        int uid = Binder.getCallingUid();
15314        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15315        // reader
15316        synchronized (mPackages) {
15317            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15318        }
15319    }
15320
15321    @Override
15322    public void enterSafeMode() {
15323        enforceSystemOrRoot("Only the system can request entering safe mode");
15324
15325        if (!mSystemReady) {
15326            mSafeMode = true;
15327        }
15328    }
15329
15330    @Override
15331    public void systemReady() {
15332        mSystemReady = true;
15333
15334        // Read the compatibilty setting when the system is ready.
15335        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15336                mContext.getContentResolver(),
15337                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15338        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15339        if (DEBUG_SETTINGS) {
15340            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15341        }
15342
15343        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15344
15345        synchronized (mPackages) {
15346            // Verify that all of the preferred activity components actually
15347            // exist.  It is possible for applications to be updated and at
15348            // that point remove a previously declared activity component that
15349            // had been set as a preferred activity.  We try to clean this up
15350            // the next time we encounter that preferred activity, but it is
15351            // possible for the user flow to never be able to return to that
15352            // situation so here we do a sanity check to make sure we haven't
15353            // left any junk around.
15354            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15355            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15356                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15357                removed.clear();
15358                for (PreferredActivity pa : pir.filterSet()) {
15359                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15360                        removed.add(pa);
15361                    }
15362                }
15363                if (removed.size() > 0) {
15364                    for (int r=0; r<removed.size(); r++) {
15365                        PreferredActivity pa = removed.get(r);
15366                        Slog.w(TAG, "Removing dangling preferred activity: "
15367                                + pa.mPref.mComponent);
15368                        pir.removeFilter(pa);
15369                    }
15370                    mSettings.writePackageRestrictionsLPr(
15371                            mSettings.mPreferredActivities.keyAt(i));
15372                }
15373            }
15374
15375            for (int userId : UserManagerService.getInstance().getUserIds()) {
15376                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15377                    grantPermissionsUserIds = ArrayUtils.appendInt(
15378                            grantPermissionsUserIds, userId);
15379                }
15380            }
15381        }
15382        sUserManager.systemReady();
15383
15384        // If we upgraded grant all default permissions before kicking off.
15385        for (int userId : grantPermissionsUserIds) {
15386            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15387        }
15388
15389        // Kick off any messages waiting for system ready
15390        if (mPostSystemReadyMessages != null) {
15391            for (Message msg : mPostSystemReadyMessages) {
15392                msg.sendToTarget();
15393            }
15394            mPostSystemReadyMessages = null;
15395        }
15396
15397        // Watch for external volumes that come and go over time
15398        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15399        storage.registerListener(mStorageListener);
15400
15401        mInstallerService.systemReady();
15402        mPackageDexOptimizer.systemReady();
15403
15404        MountServiceInternal mountServiceInternal = LocalServices.getService(
15405                MountServiceInternal.class);
15406        mountServiceInternal.addExternalStoragePolicy(
15407                new MountServiceInternal.ExternalStorageMountPolicy() {
15408            @Override
15409            public int getMountMode(int uid, String packageName) {
15410                if (Process.isIsolated(uid)) {
15411                    return Zygote.MOUNT_EXTERNAL_NONE;
15412                }
15413                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15414                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15415                }
15416                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15417                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15418                }
15419                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15420                    return Zygote.MOUNT_EXTERNAL_READ;
15421                }
15422                return Zygote.MOUNT_EXTERNAL_WRITE;
15423            }
15424
15425            @Override
15426            public boolean hasExternalStorage(int uid, String packageName) {
15427                return true;
15428            }
15429        });
15430    }
15431
15432    @Override
15433    public boolean isSafeMode() {
15434        return mSafeMode;
15435    }
15436
15437    @Override
15438    public boolean hasSystemUidErrors() {
15439        return mHasSystemUidErrors;
15440    }
15441
15442    static String arrayToString(int[] array) {
15443        StringBuffer buf = new StringBuffer(128);
15444        buf.append('[');
15445        if (array != null) {
15446            for (int i=0; i<array.length; i++) {
15447                if (i > 0) buf.append(", ");
15448                buf.append(array[i]);
15449            }
15450        }
15451        buf.append(']');
15452        return buf.toString();
15453    }
15454
15455    static class DumpState {
15456        public static final int DUMP_LIBS = 1 << 0;
15457        public static final int DUMP_FEATURES = 1 << 1;
15458        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15459        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15460        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15461        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15462        public static final int DUMP_PERMISSIONS = 1 << 6;
15463        public static final int DUMP_PACKAGES = 1 << 7;
15464        public static final int DUMP_SHARED_USERS = 1 << 8;
15465        public static final int DUMP_MESSAGES = 1 << 9;
15466        public static final int DUMP_PROVIDERS = 1 << 10;
15467        public static final int DUMP_VERIFIERS = 1 << 11;
15468        public static final int DUMP_PREFERRED = 1 << 12;
15469        public static final int DUMP_PREFERRED_XML = 1 << 13;
15470        public static final int DUMP_KEYSETS = 1 << 14;
15471        public static final int DUMP_VERSION = 1 << 15;
15472        public static final int DUMP_INSTALLS = 1 << 16;
15473        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15474        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15475
15476        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15477
15478        private int mTypes;
15479
15480        private int mOptions;
15481
15482        private boolean mTitlePrinted;
15483
15484        private SharedUserSetting mSharedUser;
15485
15486        public boolean isDumping(int type) {
15487            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15488                return true;
15489            }
15490
15491            return (mTypes & type) != 0;
15492        }
15493
15494        public void setDump(int type) {
15495            mTypes |= type;
15496        }
15497
15498        public boolean isOptionEnabled(int option) {
15499            return (mOptions & option) != 0;
15500        }
15501
15502        public void setOptionEnabled(int option) {
15503            mOptions |= option;
15504        }
15505
15506        public boolean onTitlePrinted() {
15507            final boolean printed = mTitlePrinted;
15508            mTitlePrinted = true;
15509            return printed;
15510        }
15511
15512        public boolean getTitlePrinted() {
15513            return mTitlePrinted;
15514        }
15515
15516        public void setTitlePrinted(boolean enabled) {
15517            mTitlePrinted = enabled;
15518        }
15519
15520        public SharedUserSetting getSharedUser() {
15521            return mSharedUser;
15522        }
15523
15524        public void setSharedUser(SharedUserSetting user) {
15525            mSharedUser = user;
15526        }
15527    }
15528
15529    @Override
15530    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15531            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15532        (new PackageManagerShellCommand(this)).exec(
15533                this, in, out, err, args, resultReceiver);
15534    }
15535
15536    @Override
15537    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15538        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15539                != PackageManager.PERMISSION_GRANTED) {
15540            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15541                    + Binder.getCallingPid()
15542                    + ", uid=" + Binder.getCallingUid()
15543                    + " without permission "
15544                    + android.Manifest.permission.DUMP);
15545            return;
15546        }
15547
15548        DumpState dumpState = new DumpState();
15549        boolean fullPreferred = false;
15550        boolean checkin = false;
15551
15552        String packageName = null;
15553        ArraySet<String> permissionNames = null;
15554
15555        int opti = 0;
15556        while (opti < args.length) {
15557            String opt = args[opti];
15558            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15559                break;
15560            }
15561            opti++;
15562
15563            if ("-a".equals(opt)) {
15564                // Right now we only know how to print all.
15565            } else if ("-h".equals(opt)) {
15566                pw.println("Package manager dump options:");
15567                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15568                pw.println("    --checkin: dump for a checkin");
15569                pw.println("    -f: print details of intent filters");
15570                pw.println("    -h: print this help");
15571                pw.println("  cmd may be one of:");
15572                pw.println("    l[ibraries]: list known shared libraries");
15573                pw.println("    f[eatures]: list device features");
15574                pw.println("    k[eysets]: print known keysets");
15575                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15576                pw.println("    perm[issions]: dump permissions");
15577                pw.println("    permission [name ...]: dump declaration and use of given permission");
15578                pw.println("    pref[erred]: print preferred package settings");
15579                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15580                pw.println("    prov[iders]: dump content providers");
15581                pw.println("    p[ackages]: dump installed packages");
15582                pw.println("    s[hared-users]: dump shared user IDs");
15583                pw.println("    m[essages]: print collected runtime messages");
15584                pw.println("    v[erifiers]: print package verifier info");
15585                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15586                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15587                pw.println("    version: print database version info");
15588                pw.println("    write: write current settings now");
15589                pw.println("    installs: details about install sessions");
15590                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15591                pw.println("    <package.name>: info about given package");
15592                return;
15593            } else if ("--checkin".equals(opt)) {
15594                checkin = true;
15595            } else if ("-f".equals(opt)) {
15596                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15597            } else {
15598                pw.println("Unknown argument: " + opt + "; use -h for help");
15599            }
15600        }
15601
15602        // Is the caller requesting to dump a particular piece of data?
15603        if (opti < args.length) {
15604            String cmd = args[opti];
15605            opti++;
15606            // Is this a package name?
15607            if ("android".equals(cmd) || cmd.contains(".")) {
15608                packageName = cmd;
15609                // When dumping a single package, we always dump all of its
15610                // filter information since the amount of data will be reasonable.
15611                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15612            } else if ("check-permission".equals(cmd)) {
15613                if (opti >= args.length) {
15614                    pw.println("Error: check-permission missing permission argument");
15615                    return;
15616                }
15617                String perm = args[opti];
15618                opti++;
15619                if (opti >= args.length) {
15620                    pw.println("Error: check-permission missing package argument");
15621                    return;
15622                }
15623                String pkg = args[opti];
15624                opti++;
15625                int user = UserHandle.getUserId(Binder.getCallingUid());
15626                if (opti < args.length) {
15627                    try {
15628                        user = Integer.parseInt(args[opti]);
15629                    } catch (NumberFormatException e) {
15630                        pw.println("Error: check-permission user argument is not a number: "
15631                                + args[opti]);
15632                        return;
15633                    }
15634                }
15635                pw.println(checkPermission(perm, pkg, user));
15636                return;
15637            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15638                dumpState.setDump(DumpState.DUMP_LIBS);
15639            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15640                dumpState.setDump(DumpState.DUMP_FEATURES);
15641            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15642                if (opti >= args.length) {
15643                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15644                            | DumpState.DUMP_SERVICE_RESOLVERS
15645                            | DumpState.DUMP_RECEIVER_RESOLVERS
15646                            | DumpState.DUMP_CONTENT_RESOLVERS);
15647                } else {
15648                    while (opti < args.length) {
15649                        String name = args[opti];
15650                        if ("a".equals(name) || "activity".equals(name)) {
15651                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15652                        } else if ("s".equals(name) || "service".equals(name)) {
15653                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15654                        } else if ("r".equals(name) || "receiver".equals(name)) {
15655                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15656                        } else if ("c".equals(name) || "content".equals(name)) {
15657                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15658                        } else {
15659                            pw.println("Error: unknown resolver table type: " + name);
15660                            return;
15661                        }
15662                        opti++;
15663                    }
15664                }
15665            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15666                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15667            } else if ("permission".equals(cmd)) {
15668                if (opti >= args.length) {
15669                    pw.println("Error: permission requires permission name");
15670                    return;
15671                }
15672                permissionNames = new ArraySet<>();
15673                while (opti < args.length) {
15674                    permissionNames.add(args[opti]);
15675                    opti++;
15676                }
15677                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15678                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15679            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15680                dumpState.setDump(DumpState.DUMP_PREFERRED);
15681            } else if ("preferred-xml".equals(cmd)) {
15682                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15683                if (opti < args.length && "--full".equals(args[opti])) {
15684                    fullPreferred = true;
15685                    opti++;
15686                }
15687            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15688                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15689            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15690                dumpState.setDump(DumpState.DUMP_PACKAGES);
15691            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15692                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15693            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15694                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15695            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15696                dumpState.setDump(DumpState.DUMP_MESSAGES);
15697            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15698                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15699            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15700                    || "intent-filter-verifiers".equals(cmd)) {
15701                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15702            } else if ("version".equals(cmd)) {
15703                dumpState.setDump(DumpState.DUMP_VERSION);
15704            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15705                dumpState.setDump(DumpState.DUMP_KEYSETS);
15706            } else if ("installs".equals(cmd)) {
15707                dumpState.setDump(DumpState.DUMP_INSTALLS);
15708            } else if ("write".equals(cmd)) {
15709                synchronized (mPackages) {
15710                    mSettings.writeLPr();
15711                    pw.println("Settings written.");
15712                    return;
15713                }
15714            }
15715        }
15716
15717        if (checkin) {
15718            pw.println("vers,1");
15719        }
15720
15721        // reader
15722        synchronized (mPackages) {
15723            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15724                if (!checkin) {
15725                    if (dumpState.onTitlePrinted())
15726                        pw.println();
15727                    pw.println("Database versions:");
15728                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15729                }
15730            }
15731
15732            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15733                if (!checkin) {
15734                    if (dumpState.onTitlePrinted())
15735                        pw.println();
15736                    pw.println("Verifiers:");
15737                    pw.print("  Required: ");
15738                    pw.print(mRequiredVerifierPackage);
15739                    pw.print(" (uid=");
15740                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15741                            UserHandle.USER_SYSTEM));
15742                    pw.println(")");
15743                } else if (mRequiredVerifierPackage != null) {
15744                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15745                    pw.print(",");
15746                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15747                            UserHandle.USER_SYSTEM));
15748                }
15749            }
15750
15751            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15752                    packageName == null) {
15753                if (mIntentFilterVerifierComponent != null) {
15754                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15755                    if (!checkin) {
15756                        if (dumpState.onTitlePrinted())
15757                            pw.println();
15758                        pw.println("Intent Filter Verifier:");
15759                        pw.print("  Using: ");
15760                        pw.print(verifierPackageName);
15761                        pw.print(" (uid=");
15762                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15763                                UserHandle.USER_SYSTEM));
15764                        pw.println(")");
15765                    } else if (verifierPackageName != null) {
15766                        pw.print("ifv,"); pw.print(verifierPackageName);
15767                        pw.print(",");
15768                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15769                                UserHandle.USER_SYSTEM));
15770                    }
15771                } else {
15772                    pw.println();
15773                    pw.println("No Intent Filter Verifier available!");
15774                }
15775            }
15776
15777            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15778                boolean printedHeader = false;
15779                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15780                while (it.hasNext()) {
15781                    String name = it.next();
15782                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15783                    if (!checkin) {
15784                        if (!printedHeader) {
15785                            if (dumpState.onTitlePrinted())
15786                                pw.println();
15787                            pw.println("Libraries:");
15788                            printedHeader = true;
15789                        }
15790                        pw.print("  ");
15791                    } else {
15792                        pw.print("lib,");
15793                    }
15794                    pw.print(name);
15795                    if (!checkin) {
15796                        pw.print(" -> ");
15797                    }
15798                    if (ent.path != null) {
15799                        if (!checkin) {
15800                            pw.print("(jar) ");
15801                            pw.print(ent.path);
15802                        } else {
15803                            pw.print(",jar,");
15804                            pw.print(ent.path);
15805                        }
15806                    } else {
15807                        if (!checkin) {
15808                            pw.print("(apk) ");
15809                            pw.print(ent.apk);
15810                        } else {
15811                            pw.print(",apk,");
15812                            pw.print(ent.apk);
15813                        }
15814                    }
15815                    pw.println();
15816                }
15817            }
15818
15819            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15820                if (dumpState.onTitlePrinted())
15821                    pw.println();
15822                if (!checkin) {
15823                    pw.println("Features:");
15824                }
15825                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15826                while (it.hasNext()) {
15827                    String name = it.next();
15828                    if (!checkin) {
15829                        pw.print("  ");
15830                    } else {
15831                        pw.print("feat,");
15832                    }
15833                    pw.println(name);
15834                }
15835            }
15836
15837            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15838                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15839                        : "Activity Resolver Table:", "  ", packageName,
15840                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15841                    dumpState.setTitlePrinted(true);
15842                }
15843            }
15844            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15845                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15846                        : "Receiver Resolver Table:", "  ", packageName,
15847                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15848                    dumpState.setTitlePrinted(true);
15849                }
15850            }
15851            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15852                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15853                        : "Service Resolver Table:", "  ", packageName,
15854                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15855                    dumpState.setTitlePrinted(true);
15856                }
15857            }
15858            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15859                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15860                        : "Provider Resolver Table:", "  ", packageName,
15861                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15862                    dumpState.setTitlePrinted(true);
15863                }
15864            }
15865
15866            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15867                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15868                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15869                    int user = mSettings.mPreferredActivities.keyAt(i);
15870                    if (pir.dump(pw,
15871                            dumpState.getTitlePrinted()
15872                                ? "\nPreferred Activities User " + user + ":"
15873                                : "Preferred Activities User " + user + ":", "  ",
15874                            packageName, true, false)) {
15875                        dumpState.setTitlePrinted(true);
15876                    }
15877                }
15878            }
15879
15880            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15881                pw.flush();
15882                FileOutputStream fout = new FileOutputStream(fd);
15883                BufferedOutputStream str = new BufferedOutputStream(fout);
15884                XmlSerializer serializer = new FastXmlSerializer();
15885                try {
15886                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15887                    serializer.startDocument(null, true);
15888                    serializer.setFeature(
15889                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15890                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15891                    serializer.endDocument();
15892                    serializer.flush();
15893                } catch (IllegalArgumentException e) {
15894                    pw.println("Failed writing: " + e);
15895                } catch (IllegalStateException e) {
15896                    pw.println("Failed writing: " + e);
15897                } catch (IOException e) {
15898                    pw.println("Failed writing: " + e);
15899                }
15900            }
15901
15902            if (!checkin
15903                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15904                    && packageName == null) {
15905                pw.println();
15906                int count = mSettings.mPackages.size();
15907                if (count == 0) {
15908                    pw.println("No applications!");
15909                    pw.println();
15910                } else {
15911                    final String prefix = "  ";
15912                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15913                    if (allPackageSettings.size() == 0) {
15914                        pw.println("No domain preferred apps!");
15915                        pw.println();
15916                    } else {
15917                        pw.println("App verification status:");
15918                        pw.println();
15919                        count = 0;
15920                        for (PackageSetting ps : allPackageSettings) {
15921                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15922                            if (ivi == null || ivi.getPackageName() == null) continue;
15923                            pw.println(prefix + "Package: " + ivi.getPackageName());
15924                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15925                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15926                            pw.println();
15927                            count++;
15928                        }
15929                        if (count == 0) {
15930                            pw.println(prefix + "No app verification established.");
15931                            pw.println();
15932                        }
15933                        for (int userId : sUserManager.getUserIds()) {
15934                            pw.println("App linkages for user " + userId + ":");
15935                            pw.println();
15936                            count = 0;
15937                            for (PackageSetting ps : allPackageSettings) {
15938                                final long status = ps.getDomainVerificationStatusForUser(userId);
15939                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15940                                    continue;
15941                                }
15942                                pw.println(prefix + "Package: " + ps.name);
15943                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15944                                String statusStr = IntentFilterVerificationInfo.
15945                                        getStatusStringFromValue(status);
15946                                pw.println(prefix + "Status:  " + statusStr);
15947                                pw.println();
15948                                count++;
15949                            }
15950                            if (count == 0) {
15951                                pw.println(prefix + "No configured app linkages.");
15952                                pw.println();
15953                            }
15954                        }
15955                    }
15956                }
15957            }
15958
15959            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15960                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15961                if (packageName == null && permissionNames == null) {
15962                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15963                        if (iperm == 0) {
15964                            if (dumpState.onTitlePrinted())
15965                                pw.println();
15966                            pw.println("AppOp Permissions:");
15967                        }
15968                        pw.print("  AppOp Permission ");
15969                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15970                        pw.println(":");
15971                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15972                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15973                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15974                        }
15975                    }
15976                }
15977            }
15978
15979            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15980                boolean printedSomething = false;
15981                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15982                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15983                        continue;
15984                    }
15985                    if (!printedSomething) {
15986                        if (dumpState.onTitlePrinted())
15987                            pw.println();
15988                        pw.println("Registered ContentProviders:");
15989                        printedSomething = true;
15990                    }
15991                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15992                    pw.print("    "); pw.println(p.toString());
15993                }
15994                printedSomething = false;
15995                for (Map.Entry<String, PackageParser.Provider> entry :
15996                        mProvidersByAuthority.entrySet()) {
15997                    PackageParser.Provider p = entry.getValue();
15998                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15999                        continue;
16000                    }
16001                    if (!printedSomething) {
16002                        if (dumpState.onTitlePrinted())
16003                            pw.println();
16004                        pw.println("ContentProvider Authorities:");
16005                        printedSomething = true;
16006                    }
16007                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16008                    pw.print("    "); pw.println(p.toString());
16009                    if (p.info != null && p.info.applicationInfo != null) {
16010                        final String appInfo = p.info.applicationInfo.toString();
16011                        pw.print("      applicationInfo="); pw.println(appInfo);
16012                    }
16013                }
16014            }
16015
16016            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16017                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16018            }
16019
16020            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16021                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16022            }
16023
16024            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16025                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16026            }
16027
16028            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16029                // XXX should handle packageName != null by dumping only install data that
16030                // the given package is involved with.
16031                if (dumpState.onTitlePrinted()) pw.println();
16032                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16033            }
16034
16035            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16036                if (dumpState.onTitlePrinted()) pw.println();
16037                mSettings.dumpReadMessagesLPr(pw, dumpState);
16038
16039                pw.println();
16040                pw.println("Package warning messages:");
16041                BufferedReader in = null;
16042                String line = null;
16043                try {
16044                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16045                    while ((line = in.readLine()) != null) {
16046                        if (line.contains("ignored: updated version")) continue;
16047                        pw.println(line);
16048                    }
16049                } catch (IOException ignored) {
16050                } finally {
16051                    IoUtils.closeQuietly(in);
16052                }
16053            }
16054
16055            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16056                BufferedReader in = null;
16057                String line = null;
16058                try {
16059                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16060                    while ((line = in.readLine()) != null) {
16061                        if (line.contains("ignored: updated version")) continue;
16062                        pw.print("msg,");
16063                        pw.println(line);
16064                    }
16065                } catch (IOException ignored) {
16066                } finally {
16067                    IoUtils.closeQuietly(in);
16068                }
16069            }
16070        }
16071    }
16072
16073    private String dumpDomainString(String packageName) {
16074        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16075        List<IntentFilter> filters = getAllIntentFilters(packageName);
16076
16077        ArraySet<String> result = new ArraySet<>();
16078        if (iviList.size() > 0) {
16079            for (IntentFilterVerificationInfo ivi : iviList) {
16080                for (String host : ivi.getDomains()) {
16081                    result.add(host);
16082                }
16083            }
16084        }
16085        if (filters != null && filters.size() > 0) {
16086            for (IntentFilter filter : filters) {
16087                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16088                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16089                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16090                    result.addAll(filter.getHostsList());
16091                }
16092            }
16093        }
16094
16095        StringBuilder sb = new StringBuilder(result.size() * 16);
16096        for (String domain : result) {
16097            if (sb.length() > 0) sb.append(" ");
16098            sb.append(domain);
16099        }
16100        return sb.toString();
16101    }
16102
16103    // ------- apps on sdcard specific code -------
16104    static final boolean DEBUG_SD_INSTALL = false;
16105
16106    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16107
16108    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16109
16110    private boolean mMediaMounted = false;
16111
16112    static String getEncryptKey() {
16113        try {
16114            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16115                    SD_ENCRYPTION_KEYSTORE_NAME);
16116            if (sdEncKey == null) {
16117                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16118                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16119                if (sdEncKey == null) {
16120                    Slog.e(TAG, "Failed to create encryption keys");
16121                    return null;
16122                }
16123            }
16124            return sdEncKey;
16125        } catch (NoSuchAlgorithmException nsae) {
16126            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16127            return null;
16128        } catch (IOException ioe) {
16129            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16130            return null;
16131        }
16132    }
16133
16134    /*
16135     * Update media status on PackageManager.
16136     */
16137    @Override
16138    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16139        int callingUid = Binder.getCallingUid();
16140        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16141            throw new SecurityException("Media status can only be updated by the system");
16142        }
16143        // reader; this apparently protects mMediaMounted, but should probably
16144        // be a different lock in that case.
16145        synchronized (mPackages) {
16146            Log.i(TAG, "Updating external media status from "
16147                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16148                    + (mediaStatus ? "mounted" : "unmounted"));
16149            if (DEBUG_SD_INSTALL)
16150                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16151                        + ", mMediaMounted=" + mMediaMounted);
16152            if (mediaStatus == mMediaMounted) {
16153                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16154                        : 0, -1);
16155                mHandler.sendMessage(msg);
16156                return;
16157            }
16158            mMediaMounted = mediaStatus;
16159        }
16160        // Queue up an async operation since the package installation may take a
16161        // little while.
16162        mHandler.post(new Runnable() {
16163            public void run() {
16164                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16165            }
16166        });
16167    }
16168
16169    /**
16170     * Called by MountService when the initial ASECs to scan are available.
16171     * Should block until all the ASEC containers are finished being scanned.
16172     */
16173    public void scanAvailableAsecs() {
16174        updateExternalMediaStatusInner(true, false, false);
16175        if (mShouldRestoreconData) {
16176            SELinuxMMAC.setRestoreconDone();
16177            mShouldRestoreconData = false;
16178        }
16179    }
16180
16181    /*
16182     * Collect information of applications on external media, map them against
16183     * existing containers and update information based on current mount status.
16184     * Please note that we always have to report status if reportStatus has been
16185     * set to true especially when unloading packages.
16186     */
16187    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16188            boolean externalStorage) {
16189        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16190        int[] uidArr = EmptyArray.INT;
16191
16192        final String[] list = PackageHelper.getSecureContainerList();
16193        if (ArrayUtils.isEmpty(list)) {
16194            Log.i(TAG, "No secure containers found");
16195        } else {
16196            // Process list of secure containers and categorize them
16197            // as active or stale based on their package internal state.
16198
16199            // reader
16200            synchronized (mPackages) {
16201                for (String cid : list) {
16202                    // Leave stages untouched for now; installer service owns them
16203                    if (PackageInstallerService.isStageName(cid)) continue;
16204
16205                    if (DEBUG_SD_INSTALL)
16206                        Log.i(TAG, "Processing container " + cid);
16207                    String pkgName = getAsecPackageName(cid);
16208                    if (pkgName == null) {
16209                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16210                        continue;
16211                    }
16212                    if (DEBUG_SD_INSTALL)
16213                        Log.i(TAG, "Looking for pkg : " + pkgName);
16214
16215                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16216                    if (ps == null) {
16217                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16218                        continue;
16219                    }
16220
16221                    /*
16222                     * Skip packages that are not external if we're unmounting
16223                     * external storage.
16224                     */
16225                    if (externalStorage && !isMounted && !isExternal(ps)) {
16226                        continue;
16227                    }
16228
16229                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16230                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16231                    // The package status is changed only if the code path
16232                    // matches between settings and the container id.
16233                    if (ps.codePathString != null
16234                            && ps.codePathString.startsWith(args.getCodePath())) {
16235                        if (DEBUG_SD_INSTALL) {
16236                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16237                                    + " at code path: " + ps.codePathString);
16238                        }
16239
16240                        // We do have a valid package installed on sdcard
16241                        processCids.put(args, ps.codePathString);
16242                        final int uid = ps.appId;
16243                        if (uid != -1) {
16244                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16245                        }
16246                    } else {
16247                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16248                                + ps.codePathString);
16249                    }
16250                }
16251            }
16252
16253            Arrays.sort(uidArr);
16254        }
16255
16256        // Process packages with valid entries.
16257        if (isMounted) {
16258            if (DEBUG_SD_INSTALL)
16259                Log.i(TAG, "Loading packages");
16260            loadMediaPackages(processCids, uidArr, externalStorage);
16261            startCleaningPackages();
16262            mInstallerService.onSecureContainersAvailable();
16263        } else {
16264            if (DEBUG_SD_INSTALL)
16265                Log.i(TAG, "Unloading packages");
16266            unloadMediaPackages(processCids, uidArr, reportStatus);
16267        }
16268    }
16269
16270    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16271            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16272        final int size = infos.size();
16273        final String[] packageNames = new String[size];
16274        final int[] packageUids = new int[size];
16275        for (int i = 0; i < size; i++) {
16276            final ApplicationInfo info = infos.get(i);
16277            packageNames[i] = info.packageName;
16278            packageUids[i] = info.uid;
16279        }
16280        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16281                finishedReceiver);
16282    }
16283
16284    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16285            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16286        sendResourcesChangedBroadcast(mediaStatus, replacing,
16287                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16288    }
16289
16290    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16291            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16292        int size = pkgList.length;
16293        if (size > 0) {
16294            // Send broadcasts here
16295            Bundle extras = new Bundle();
16296            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16297            if (uidArr != null) {
16298                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16299            }
16300            if (replacing) {
16301                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16302            }
16303            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16304                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16305            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16306        }
16307    }
16308
16309   /*
16310     * Look at potentially valid container ids from processCids If package
16311     * information doesn't match the one on record or package scanning fails,
16312     * the cid is added to list of removeCids. We currently don't delete stale
16313     * containers.
16314     */
16315    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16316            boolean externalStorage) {
16317        ArrayList<String> pkgList = new ArrayList<String>();
16318        Set<AsecInstallArgs> keys = processCids.keySet();
16319
16320        for (AsecInstallArgs args : keys) {
16321            String codePath = processCids.get(args);
16322            if (DEBUG_SD_INSTALL)
16323                Log.i(TAG, "Loading container : " + args.cid);
16324            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16325            try {
16326                // Make sure there are no container errors first.
16327                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16328                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16329                            + " when installing from sdcard");
16330                    continue;
16331                }
16332                // Check code path here.
16333                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16334                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16335                            + " does not match one in settings " + codePath);
16336                    continue;
16337                }
16338                // Parse package
16339                int parseFlags = mDefParseFlags;
16340                if (args.isExternalAsec()) {
16341                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16342                }
16343                if (args.isFwdLocked()) {
16344                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16345                }
16346
16347                synchronized (mInstallLock) {
16348                    PackageParser.Package pkg = null;
16349                    try {
16350                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16351                    } catch (PackageManagerException e) {
16352                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16353                    }
16354                    // Scan the package
16355                    if (pkg != null) {
16356                        /*
16357                         * TODO why is the lock being held? doPostInstall is
16358                         * called in other places without the lock. This needs
16359                         * to be straightened out.
16360                         */
16361                        // writer
16362                        synchronized (mPackages) {
16363                            retCode = PackageManager.INSTALL_SUCCEEDED;
16364                            pkgList.add(pkg.packageName);
16365                            // Post process args
16366                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16367                                    pkg.applicationInfo.uid);
16368                        }
16369                    } else {
16370                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16371                    }
16372                }
16373
16374            } finally {
16375                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16376                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16377                }
16378            }
16379        }
16380        // writer
16381        synchronized (mPackages) {
16382            // If the platform SDK has changed since the last time we booted,
16383            // we need to re-grant app permission to catch any new ones that
16384            // appear. This is really a hack, and means that apps can in some
16385            // cases get permissions that the user didn't initially explicitly
16386            // allow... it would be nice to have some better way to handle
16387            // this situation.
16388            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16389                    : mSettings.getInternalVersion();
16390            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16391                    : StorageManager.UUID_PRIVATE_INTERNAL;
16392
16393            int updateFlags = UPDATE_PERMISSIONS_ALL;
16394            if (ver.sdkVersion != mSdkVersion) {
16395                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16396                        + mSdkVersion + "; regranting permissions for external");
16397                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16398            }
16399            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16400
16401            // Yay, everything is now upgraded
16402            ver.forceCurrent();
16403
16404            // can downgrade to reader
16405            // Persist settings
16406            mSettings.writeLPr();
16407        }
16408        // Send a broadcast to let everyone know we are done processing
16409        if (pkgList.size() > 0) {
16410            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16411        }
16412    }
16413
16414   /*
16415     * Utility method to unload a list of specified containers
16416     */
16417    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16418        // Just unmount all valid containers.
16419        for (AsecInstallArgs arg : cidArgs) {
16420            synchronized (mInstallLock) {
16421                arg.doPostDeleteLI(false);
16422           }
16423       }
16424   }
16425
16426    /*
16427     * Unload packages mounted on external media. This involves deleting package
16428     * data from internal structures, sending broadcasts about diabled packages,
16429     * gc'ing to free up references, unmounting all secure containers
16430     * corresponding to packages on external media, and posting a
16431     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16432     * that we always have to post this message if status has been requested no
16433     * matter what.
16434     */
16435    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16436            final boolean reportStatus) {
16437        if (DEBUG_SD_INSTALL)
16438            Log.i(TAG, "unloading media packages");
16439        ArrayList<String> pkgList = new ArrayList<String>();
16440        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16441        final Set<AsecInstallArgs> keys = processCids.keySet();
16442        for (AsecInstallArgs args : keys) {
16443            String pkgName = args.getPackageName();
16444            if (DEBUG_SD_INSTALL)
16445                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16446            // Delete package internally
16447            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16448            synchronized (mInstallLock) {
16449                boolean res = deletePackageLI(pkgName, null, false, null, null,
16450                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16451                if (res) {
16452                    pkgList.add(pkgName);
16453                } else {
16454                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16455                    failedList.add(args);
16456                }
16457            }
16458        }
16459
16460        // reader
16461        synchronized (mPackages) {
16462            // We didn't update the settings after removing each package;
16463            // write them now for all packages.
16464            mSettings.writeLPr();
16465        }
16466
16467        // We have to absolutely send UPDATED_MEDIA_STATUS only
16468        // after confirming that all the receivers processed the ordered
16469        // broadcast when packages get disabled, force a gc to clean things up.
16470        // and unload all the containers.
16471        if (pkgList.size() > 0) {
16472            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16473                    new IIntentReceiver.Stub() {
16474                public void performReceive(Intent intent, int resultCode, String data,
16475                        Bundle extras, boolean ordered, boolean sticky,
16476                        int sendingUser) throws RemoteException {
16477                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16478                            reportStatus ? 1 : 0, 1, keys);
16479                    mHandler.sendMessage(msg);
16480                }
16481            });
16482        } else {
16483            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16484                    keys);
16485            mHandler.sendMessage(msg);
16486        }
16487    }
16488
16489    private void loadPrivatePackages(final VolumeInfo vol) {
16490        mHandler.post(new Runnable() {
16491            @Override
16492            public void run() {
16493                loadPrivatePackagesInner(vol);
16494            }
16495        });
16496    }
16497
16498    private void loadPrivatePackagesInner(VolumeInfo vol) {
16499        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16500        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16501
16502        final VersionInfo ver;
16503        final List<PackageSetting> packages;
16504        synchronized (mPackages) {
16505            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16506            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16507        }
16508
16509        for (PackageSetting ps : packages) {
16510            synchronized (mInstallLock) {
16511                final PackageParser.Package pkg;
16512                try {
16513                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16514                    loaded.add(pkg.applicationInfo);
16515                } catch (PackageManagerException e) {
16516                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16517                }
16518
16519                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16520                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16521                }
16522            }
16523        }
16524
16525        synchronized (mPackages) {
16526            int updateFlags = UPDATE_PERMISSIONS_ALL;
16527            if (ver.sdkVersion != mSdkVersion) {
16528                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16529                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16530                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16531            }
16532            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16533
16534            // Yay, everything is now upgraded
16535            ver.forceCurrent();
16536
16537            mSettings.writeLPr();
16538        }
16539
16540        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16541        sendResourcesChangedBroadcast(true, false, loaded, null);
16542    }
16543
16544    private void unloadPrivatePackages(final VolumeInfo vol) {
16545        mHandler.post(new Runnable() {
16546            @Override
16547            public void run() {
16548                unloadPrivatePackagesInner(vol);
16549            }
16550        });
16551    }
16552
16553    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16554        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16555        synchronized (mInstallLock) {
16556        synchronized (mPackages) {
16557            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16558            for (PackageSetting ps : packages) {
16559                if (ps.pkg == null) continue;
16560
16561                final ApplicationInfo info = ps.pkg.applicationInfo;
16562                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16563                if (deletePackageLI(ps.name, null, false, null, null,
16564                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16565                    unloaded.add(info);
16566                } else {
16567                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16568                }
16569            }
16570
16571            mSettings.writeLPr();
16572        }
16573        }
16574
16575        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16576        sendResourcesChangedBroadcast(false, false, unloaded, null);
16577    }
16578
16579    /**
16580     * Examine all users present on given mounted volume, and destroy data
16581     * belonging to users that are no longer valid, or whose user ID has been
16582     * recycled.
16583     */
16584    private void reconcileUsers(String volumeUuid) {
16585        final File[] files = FileUtils
16586                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16587        for (File file : files) {
16588            if (!file.isDirectory()) continue;
16589
16590            final int userId;
16591            final UserInfo info;
16592            try {
16593                userId = Integer.parseInt(file.getName());
16594                info = sUserManager.getUserInfo(userId);
16595            } catch (NumberFormatException e) {
16596                Slog.w(TAG, "Invalid user directory " + file);
16597                continue;
16598            }
16599
16600            boolean destroyUser = false;
16601            if (info == null) {
16602                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16603                        + " because no matching user was found");
16604                destroyUser = true;
16605            } else {
16606                try {
16607                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16608                } catch (IOException e) {
16609                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16610                            + " because we failed to enforce serial number: " + e);
16611                    destroyUser = true;
16612                }
16613            }
16614
16615            if (destroyUser) {
16616                synchronized (mInstallLock) {
16617                    try {
16618                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16619                    } catch (InstallerException e) {
16620                        Slog.w(TAG, "Failed to clean up user dirs", e);
16621                    }
16622                }
16623            }
16624        }
16625
16626        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16627        final UserManager um = mContext.getSystemService(UserManager.class);
16628        for (UserInfo user : um.getUsers()) {
16629            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16630            if (userDir.exists()) continue;
16631
16632            try {
16633                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16634                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16635            } catch (IOException e) {
16636                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16637            }
16638        }
16639    }
16640
16641    /**
16642     * Examine all apps present on given mounted volume, and destroy apps that
16643     * aren't expected, either due to uninstallation or reinstallation on
16644     * another volume.
16645     */
16646    private void reconcileApps(String volumeUuid) {
16647        final File[] files = FileUtils
16648                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16649        for (File file : files) {
16650            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16651                    && !PackageInstallerService.isStageName(file.getName());
16652            if (!isPackage) {
16653                // Ignore entries which are not packages
16654                continue;
16655            }
16656
16657            boolean destroyApp = false;
16658            String packageName = null;
16659            try {
16660                final PackageLite pkg = PackageParser.parsePackageLite(file,
16661                        PackageParser.PARSE_MUST_BE_APK);
16662                packageName = pkg.packageName;
16663
16664                synchronized (mPackages) {
16665                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16666                    if (ps == null) {
16667                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16668                                + volumeUuid + " because we found no install record");
16669                        destroyApp = true;
16670                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16671                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16672                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16673                        destroyApp = true;
16674                    }
16675                }
16676
16677            } catch (PackageParserException e) {
16678                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16679                destroyApp = true;
16680            }
16681
16682            if (destroyApp) {
16683                synchronized (mInstallLock) {
16684                    if (packageName != null) {
16685                        removeDataDirsLI(volumeUuid, packageName);
16686                    }
16687                    removeCodePathLI(file);
16688                }
16689            }
16690        }
16691    }
16692
16693    private void unfreezePackage(String packageName) {
16694        synchronized (mPackages) {
16695            final PackageSetting ps = mSettings.mPackages.get(packageName);
16696            if (ps != null) {
16697                ps.frozen = false;
16698            }
16699        }
16700    }
16701
16702    @Override
16703    public int movePackage(final String packageName, final String volumeUuid) {
16704        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16705
16706        final int moveId = mNextMoveId.getAndIncrement();
16707        mHandler.post(new Runnable() {
16708            @Override
16709            public void run() {
16710                try {
16711                    movePackageInternal(packageName, volumeUuid, moveId);
16712                } catch (PackageManagerException e) {
16713                    Slog.w(TAG, "Failed to move " + packageName, e);
16714                    mMoveCallbacks.notifyStatusChanged(moveId,
16715                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16716                }
16717            }
16718        });
16719        return moveId;
16720    }
16721
16722    private void movePackageInternal(final String packageName, final String volumeUuid,
16723            final int moveId) throws PackageManagerException {
16724        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16725        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16726        final PackageManager pm = mContext.getPackageManager();
16727
16728        final boolean currentAsec;
16729        final String currentVolumeUuid;
16730        final File codeFile;
16731        final String installerPackageName;
16732        final String packageAbiOverride;
16733        final int appId;
16734        final String seinfo;
16735        final String label;
16736
16737        // reader
16738        synchronized (mPackages) {
16739            final PackageParser.Package pkg = mPackages.get(packageName);
16740            final PackageSetting ps = mSettings.mPackages.get(packageName);
16741            if (pkg == null || ps == null) {
16742                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16743            }
16744
16745            if (pkg.applicationInfo.isSystemApp()) {
16746                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16747                        "Cannot move system application");
16748            }
16749
16750            if (pkg.applicationInfo.isExternalAsec()) {
16751                currentAsec = true;
16752                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16753            } else if (pkg.applicationInfo.isForwardLocked()) {
16754                currentAsec = true;
16755                currentVolumeUuid = "forward_locked";
16756            } else {
16757                currentAsec = false;
16758                currentVolumeUuid = ps.volumeUuid;
16759
16760                final File probe = new File(pkg.codePath);
16761                final File probeOat = new File(probe, "oat");
16762                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16763                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16764                            "Move only supported for modern cluster style installs");
16765                }
16766            }
16767
16768            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16769                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16770                        "Package already moved to " + volumeUuid);
16771            }
16772
16773            if (ps.frozen) {
16774                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16775                        "Failed to move already frozen package");
16776            }
16777            ps.frozen = true;
16778
16779            codeFile = new File(pkg.codePath);
16780            installerPackageName = ps.installerPackageName;
16781            packageAbiOverride = ps.cpuAbiOverrideString;
16782            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16783            seinfo = pkg.applicationInfo.seinfo;
16784            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16785        }
16786
16787        // Now that we're guarded by frozen state, kill app during move
16788        final long token = Binder.clearCallingIdentity();
16789        try {
16790            killApplication(packageName, appId, "move pkg");
16791        } finally {
16792            Binder.restoreCallingIdentity(token);
16793        }
16794
16795        final Bundle extras = new Bundle();
16796        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16797        extras.putString(Intent.EXTRA_TITLE, label);
16798        mMoveCallbacks.notifyCreated(moveId, extras);
16799
16800        int installFlags;
16801        final boolean moveCompleteApp;
16802        final File measurePath;
16803
16804        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16805            installFlags = INSTALL_INTERNAL;
16806            moveCompleteApp = !currentAsec;
16807            measurePath = Environment.getDataAppDirectory(volumeUuid);
16808        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16809            installFlags = INSTALL_EXTERNAL;
16810            moveCompleteApp = false;
16811            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16812        } else {
16813            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16814            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16815                    || !volume.isMountedWritable()) {
16816                unfreezePackage(packageName);
16817                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16818                        "Move location not mounted private volume");
16819            }
16820
16821            Preconditions.checkState(!currentAsec);
16822
16823            installFlags = INSTALL_INTERNAL;
16824            moveCompleteApp = true;
16825            measurePath = Environment.getDataAppDirectory(volumeUuid);
16826        }
16827
16828        final PackageStats stats = new PackageStats(null, -1);
16829        synchronized (mInstaller) {
16830            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16831                unfreezePackage(packageName);
16832                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16833                        "Failed to measure package size");
16834            }
16835        }
16836
16837        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16838                + stats.dataSize);
16839
16840        final long startFreeBytes = measurePath.getFreeSpace();
16841        final long sizeBytes;
16842        if (moveCompleteApp) {
16843            sizeBytes = stats.codeSize + stats.dataSize;
16844        } else {
16845            sizeBytes = stats.codeSize;
16846        }
16847
16848        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16849            unfreezePackage(packageName);
16850            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16851                    "Not enough free space to move");
16852        }
16853
16854        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16855
16856        final CountDownLatch installedLatch = new CountDownLatch(1);
16857        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16858            @Override
16859            public void onUserActionRequired(Intent intent) throws RemoteException {
16860                throw new IllegalStateException();
16861            }
16862
16863            @Override
16864            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16865                    Bundle extras) throws RemoteException {
16866                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16867                        + PackageManager.installStatusToString(returnCode, msg));
16868
16869                installedLatch.countDown();
16870
16871                // Regardless of success or failure of the move operation,
16872                // always unfreeze the package
16873                unfreezePackage(packageName);
16874
16875                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16876                switch (status) {
16877                    case PackageInstaller.STATUS_SUCCESS:
16878                        mMoveCallbacks.notifyStatusChanged(moveId,
16879                                PackageManager.MOVE_SUCCEEDED);
16880                        break;
16881                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16882                        mMoveCallbacks.notifyStatusChanged(moveId,
16883                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16884                        break;
16885                    default:
16886                        mMoveCallbacks.notifyStatusChanged(moveId,
16887                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16888                        break;
16889                }
16890            }
16891        };
16892
16893        final MoveInfo move;
16894        if (moveCompleteApp) {
16895            // Kick off a thread to report progress estimates
16896            new Thread() {
16897                @Override
16898                public void run() {
16899                    while (true) {
16900                        try {
16901                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16902                                break;
16903                            }
16904                        } catch (InterruptedException ignored) {
16905                        }
16906
16907                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16908                        final int progress = 10 + (int) MathUtils.constrain(
16909                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16910                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16911                    }
16912                }
16913            }.start();
16914
16915            final String dataAppName = codeFile.getName();
16916            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16917                    dataAppName, appId, seinfo);
16918        } else {
16919            move = null;
16920        }
16921
16922        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16923
16924        final Message msg = mHandler.obtainMessage(INIT_COPY);
16925        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16926        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16927                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16928        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16929        msg.obj = params;
16930
16931        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16932                System.identityHashCode(msg.obj));
16933        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16934                System.identityHashCode(msg.obj));
16935
16936        mHandler.sendMessage(msg);
16937    }
16938
16939    @Override
16940    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16941        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16942
16943        final int realMoveId = mNextMoveId.getAndIncrement();
16944        final Bundle extras = new Bundle();
16945        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16946        mMoveCallbacks.notifyCreated(realMoveId, extras);
16947
16948        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16949            @Override
16950            public void onCreated(int moveId, Bundle extras) {
16951                // Ignored
16952            }
16953
16954            @Override
16955            public void onStatusChanged(int moveId, int status, long estMillis) {
16956                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16957            }
16958        };
16959
16960        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16961        storage.setPrimaryStorageUuid(volumeUuid, callback);
16962        return realMoveId;
16963    }
16964
16965    @Override
16966    public int getMoveStatus(int moveId) {
16967        mContext.enforceCallingOrSelfPermission(
16968                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16969        return mMoveCallbacks.mLastStatus.get(moveId);
16970    }
16971
16972    @Override
16973    public void registerMoveCallback(IPackageMoveObserver callback) {
16974        mContext.enforceCallingOrSelfPermission(
16975                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16976        mMoveCallbacks.register(callback);
16977    }
16978
16979    @Override
16980    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16981        mContext.enforceCallingOrSelfPermission(
16982                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16983        mMoveCallbacks.unregister(callback);
16984    }
16985
16986    @Override
16987    public boolean setInstallLocation(int loc) {
16988        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16989                null);
16990        if (getInstallLocation() == loc) {
16991            return true;
16992        }
16993        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16994                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16995            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16996                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16997            return true;
16998        }
16999        return false;
17000   }
17001
17002    @Override
17003    public int getInstallLocation() {
17004        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17005                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17006                PackageHelper.APP_INSTALL_AUTO);
17007    }
17008
17009    /** Called by UserManagerService */
17010    void cleanUpUser(UserManagerService userManager, int userHandle) {
17011        synchronized (mPackages) {
17012            mDirtyUsers.remove(userHandle);
17013            mUserNeedsBadging.delete(userHandle);
17014            mSettings.removeUserLPw(userHandle);
17015            mPendingBroadcasts.remove(userHandle);
17016            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17017        }
17018        synchronized (mInstallLock) {
17019            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17020            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17021                final String volumeUuid = vol.getFsUuid();
17022                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17023                try {
17024                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17025                } catch (InstallerException e) {
17026                    Slog.w(TAG, "Failed to remove user data", e);
17027                }
17028            }
17029            synchronized (mPackages) {
17030                removeUnusedPackagesLILPw(userManager, userHandle);
17031            }
17032        }
17033    }
17034
17035    /**
17036     * We're removing userHandle and would like to remove any downloaded packages
17037     * that are no longer in use by any other user.
17038     * @param userHandle the user being removed
17039     */
17040    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17041        final boolean DEBUG_CLEAN_APKS = false;
17042        int [] users = userManager.getUserIds();
17043        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17044        while (psit.hasNext()) {
17045            PackageSetting ps = psit.next();
17046            if (ps.pkg == null) {
17047                continue;
17048            }
17049            final String packageName = ps.pkg.packageName;
17050            // Skip over if system app
17051            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17052                continue;
17053            }
17054            if (DEBUG_CLEAN_APKS) {
17055                Slog.i(TAG, "Checking package " + packageName);
17056            }
17057            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17058            if (keep) {
17059                if (DEBUG_CLEAN_APKS) {
17060                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17061                }
17062            } else {
17063                for (int i = 0; i < users.length; i++) {
17064                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17065                        keep = true;
17066                        if (DEBUG_CLEAN_APKS) {
17067                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17068                                    + users[i]);
17069                        }
17070                        break;
17071                    }
17072                }
17073            }
17074            if (!keep) {
17075                if (DEBUG_CLEAN_APKS) {
17076                    Slog.i(TAG, "  Removing package " + packageName);
17077                }
17078                mHandler.post(new Runnable() {
17079                    public void run() {
17080                        deletePackageX(packageName, userHandle, 0);
17081                    } //end run
17082                });
17083            }
17084        }
17085    }
17086
17087    /** Called by UserManagerService */
17088    void createNewUser(int userHandle) {
17089        synchronized (mInstallLock) {
17090            try {
17091                mInstaller.createUserConfig(userHandle);
17092            } catch (InstallerException e) {
17093                Slog.w(TAG, "Failed to create user config", e);
17094            }
17095            mSettings.createNewUserLI(this, mInstaller, userHandle);
17096        }
17097        synchronized (mPackages) {
17098            applyFactoryDefaultBrowserLPw(userHandle);
17099            primeDomainVerificationsLPw(userHandle);
17100        }
17101    }
17102
17103    void newUserCreated(final int userHandle) {
17104        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17105        // If permission review for legacy apps is required, we represent
17106        // dagerous permissions for such apps as always granted runtime
17107        // permissions to keep per user flag state whether review is needed.
17108        // Hence, if a new user is added we have to propagate dangerous
17109        // permission grants for these legacy apps.
17110        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17111            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17112                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17113        }
17114    }
17115
17116    @Override
17117    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17118        mContext.enforceCallingOrSelfPermission(
17119                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17120                "Only package verification agents can read the verifier device identity");
17121
17122        synchronized (mPackages) {
17123            return mSettings.getVerifierDeviceIdentityLPw();
17124        }
17125    }
17126
17127    @Override
17128    public void setPermissionEnforced(String permission, boolean enforced) {
17129        // TODO: Now that we no longer change GID for storage, this should to away.
17130        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17131                "setPermissionEnforced");
17132        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17133            synchronized (mPackages) {
17134                if (mSettings.mReadExternalStorageEnforced == null
17135                        || mSettings.mReadExternalStorageEnforced != enforced) {
17136                    mSettings.mReadExternalStorageEnforced = enforced;
17137                    mSettings.writeLPr();
17138                }
17139            }
17140            // kill any non-foreground processes so we restart them and
17141            // grant/revoke the GID.
17142            final IActivityManager am = ActivityManagerNative.getDefault();
17143            if (am != null) {
17144                final long token = Binder.clearCallingIdentity();
17145                try {
17146                    am.killProcessesBelowForeground("setPermissionEnforcement");
17147                } catch (RemoteException e) {
17148                } finally {
17149                    Binder.restoreCallingIdentity(token);
17150                }
17151            }
17152        } else {
17153            throw new IllegalArgumentException("No selective enforcement for " + permission);
17154        }
17155    }
17156
17157    @Override
17158    @Deprecated
17159    public boolean isPermissionEnforced(String permission) {
17160        return true;
17161    }
17162
17163    @Override
17164    public boolean isStorageLow() {
17165        final long token = Binder.clearCallingIdentity();
17166        try {
17167            final DeviceStorageMonitorInternal
17168                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17169            if (dsm != null) {
17170                return dsm.isMemoryLow();
17171            } else {
17172                return false;
17173            }
17174        } finally {
17175            Binder.restoreCallingIdentity(token);
17176        }
17177    }
17178
17179    @Override
17180    public IPackageInstaller getPackageInstaller() {
17181        return mInstallerService;
17182    }
17183
17184    private boolean userNeedsBadging(int userId) {
17185        int index = mUserNeedsBadging.indexOfKey(userId);
17186        if (index < 0) {
17187            final UserInfo userInfo;
17188            final long token = Binder.clearCallingIdentity();
17189            try {
17190                userInfo = sUserManager.getUserInfo(userId);
17191            } finally {
17192                Binder.restoreCallingIdentity(token);
17193            }
17194            final boolean b;
17195            if (userInfo != null && userInfo.isManagedProfile()) {
17196                b = true;
17197            } else {
17198                b = false;
17199            }
17200            mUserNeedsBadging.put(userId, b);
17201            return b;
17202        }
17203        return mUserNeedsBadging.valueAt(index);
17204    }
17205
17206    @Override
17207    public KeySet getKeySetByAlias(String packageName, String alias) {
17208        if (packageName == null || alias == null) {
17209            return null;
17210        }
17211        synchronized(mPackages) {
17212            final PackageParser.Package pkg = mPackages.get(packageName);
17213            if (pkg == null) {
17214                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17215                throw new IllegalArgumentException("Unknown package: " + packageName);
17216            }
17217            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17218            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17219        }
17220    }
17221
17222    @Override
17223    public KeySet getSigningKeySet(String packageName) {
17224        if (packageName == null) {
17225            return null;
17226        }
17227        synchronized(mPackages) {
17228            final PackageParser.Package pkg = mPackages.get(packageName);
17229            if (pkg == null) {
17230                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17231                throw new IllegalArgumentException("Unknown package: " + packageName);
17232            }
17233            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17234                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17235                throw new SecurityException("May not access signing KeySet of other apps.");
17236            }
17237            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17238            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17239        }
17240    }
17241
17242    @Override
17243    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17244        if (packageName == null || ks == null) {
17245            return false;
17246        }
17247        synchronized(mPackages) {
17248            final PackageParser.Package pkg = mPackages.get(packageName);
17249            if (pkg == null) {
17250                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17251                throw new IllegalArgumentException("Unknown package: " + packageName);
17252            }
17253            IBinder ksh = ks.getToken();
17254            if (ksh instanceof KeySetHandle) {
17255                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17256                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17257            }
17258            return false;
17259        }
17260    }
17261
17262    @Override
17263    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17264        if (packageName == null || ks == null) {
17265            return false;
17266        }
17267        synchronized(mPackages) {
17268            final PackageParser.Package pkg = mPackages.get(packageName);
17269            if (pkg == null) {
17270                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17271                throw new IllegalArgumentException("Unknown package: " + packageName);
17272            }
17273            IBinder ksh = ks.getToken();
17274            if (ksh instanceof KeySetHandle) {
17275                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17276                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17277            }
17278            return false;
17279        }
17280    }
17281
17282    private void deletePackageIfUnusedLPr(final String packageName) {
17283        PackageSetting ps = mSettings.mPackages.get(packageName);
17284        if (ps == null) {
17285            return;
17286        }
17287        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17288            // TODO Implement atomic delete if package is unused
17289            // It is currently possible that the package will be deleted even if it is installed
17290            // after this method returns.
17291            mHandler.post(new Runnable() {
17292                public void run() {
17293                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17294                }
17295            });
17296        }
17297    }
17298
17299    /**
17300     * Check and throw if the given before/after packages would be considered a
17301     * downgrade.
17302     */
17303    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17304            throws PackageManagerException {
17305        if (after.versionCode < before.mVersionCode) {
17306            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17307                    "Update version code " + after.versionCode + " is older than current "
17308                    + before.mVersionCode);
17309        } else if (after.versionCode == before.mVersionCode) {
17310            if (after.baseRevisionCode < before.baseRevisionCode) {
17311                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17312                        "Update base revision code " + after.baseRevisionCode
17313                        + " is older than current " + before.baseRevisionCode);
17314            }
17315
17316            if (!ArrayUtils.isEmpty(after.splitNames)) {
17317                for (int i = 0; i < after.splitNames.length; i++) {
17318                    final String splitName = after.splitNames[i];
17319                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17320                    if (j != -1) {
17321                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17322                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17323                                    "Update split " + splitName + " revision code "
17324                                    + after.splitRevisionCodes[i] + " is older than current "
17325                                    + before.splitRevisionCodes[j]);
17326                        }
17327                    }
17328                }
17329            }
17330        }
17331    }
17332
17333    private static class MoveCallbacks extends Handler {
17334        private static final int MSG_CREATED = 1;
17335        private static final int MSG_STATUS_CHANGED = 2;
17336
17337        private final RemoteCallbackList<IPackageMoveObserver>
17338                mCallbacks = new RemoteCallbackList<>();
17339
17340        private final SparseIntArray mLastStatus = new SparseIntArray();
17341
17342        public MoveCallbacks(Looper looper) {
17343            super(looper);
17344        }
17345
17346        public void register(IPackageMoveObserver callback) {
17347            mCallbacks.register(callback);
17348        }
17349
17350        public void unregister(IPackageMoveObserver callback) {
17351            mCallbacks.unregister(callback);
17352        }
17353
17354        @Override
17355        public void handleMessage(Message msg) {
17356            final SomeArgs args = (SomeArgs) msg.obj;
17357            final int n = mCallbacks.beginBroadcast();
17358            for (int i = 0; i < n; i++) {
17359                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17360                try {
17361                    invokeCallback(callback, msg.what, args);
17362                } catch (RemoteException ignored) {
17363                }
17364            }
17365            mCallbacks.finishBroadcast();
17366            args.recycle();
17367        }
17368
17369        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17370                throws RemoteException {
17371            switch (what) {
17372                case MSG_CREATED: {
17373                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17374                    break;
17375                }
17376                case MSG_STATUS_CHANGED: {
17377                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17378                    break;
17379                }
17380            }
17381        }
17382
17383        private void notifyCreated(int moveId, Bundle extras) {
17384            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17385
17386            final SomeArgs args = SomeArgs.obtain();
17387            args.argi1 = moveId;
17388            args.arg2 = extras;
17389            obtainMessage(MSG_CREATED, args).sendToTarget();
17390        }
17391
17392        private void notifyStatusChanged(int moveId, int status) {
17393            notifyStatusChanged(moveId, status, -1);
17394        }
17395
17396        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17397            Slog.v(TAG, "Move " + moveId + " status " + status);
17398
17399            final SomeArgs args = SomeArgs.obtain();
17400            args.argi1 = moveId;
17401            args.argi2 = status;
17402            args.arg3 = estMillis;
17403            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17404
17405            synchronized (mLastStatus) {
17406                mLastStatus.put(moveId, status);
17407            }
17408        }
17409    }
17410
17411    private final static class OnPermissionChangeListeners extends Handler {
17412        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17413
17414        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17415                new RemoteCallbackList<>();
17416
17417        public OnPermissionChangeListeners(Looper looper) {
17418            super(looper);
17419        }
17420
17421        @Override
17422        public void handleMessage(Message msg) {
17423            switch (msg.what) {
17424                case MSG_ON_PERMISSIONS_CHANGED: {
17425                    final int uid = msg.arg1;
17426                    handleOnPermissionsChanged(uid);
17427                } break;
17428            }
17429        }
17430
17431        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17432            mPermissionListeners.register(listener);
17433
17434        }
17435
17436        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17437            mPermissionListeners.unregister(listener);
17438        }
17439
17440        public void onPermissionsChanged(int uid) {
17441            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17442                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17443            }
17444        }
17445
17446        private void handleOnPermissionsChanged(int uid) {
17447            final int count = mPermissionListeners.beginBroadcast();
17448            try {
17449                for (int i = 0; i < count; i++) {
17450                    IOnPermissionsChangeListener callback = mPermissionListeners
17451                            .getBroadcastItem(i);
17452                    try {
17453                        callback.onPermissionsChanged(uid);
17454                    } catch (RemoteException e) {
17455                        Log.e(TAG, "Permission listener is dead", e);
17456                    }
17457                }
17458            } finally {
17459                mPermissionListeners.finishBroadcast();
17460            }
17461        }
17462    }
17463
17464    private class PackageManagerInternalImpl extends PackageManagerInternal {
17465        @Override
17466        public void setLocationPackagesProvider(PackagesProvider provider) {
17467            synchronized (mPackages) {
17468                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17469            }
17470        }
17471
17472        @Override
17473        public void setImePackagesProvider(PackagesProvider provider) {
17474            synchronized (mPackages) {
17475                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17476            }
17477        }
17478
17479        @Override
17480        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17481            synchronized (mPackages) {
17482                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17483            }
17484        }
17485
17486        @Override
17487        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17488            synchronized (mPackages) {
17489                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17490            }
17491        }
17492
17493        @Override
17494        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17495            synchronized (mPackages) {
17496                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17497            }
17498        }
17499
17500        @Override
17501        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17502            synchronized (mPackages) {
17503                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17504            }
17505        }
17506
17507        @Override
17508        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17509            synchronized (mPackages) {
17510                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17511            }
17512        }
17513
17514        @Override
17515        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17516            synchronized (mPackages) {
17517                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17518                        packageName, userId);
17519            }
17520        }
17521
17522        @Override
17523        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17524            synchronized (mPackages) {
17525                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17526                        packageName, userId);
17527            }
17528        }
17529
17530        @Override
17531        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17532            synchronized (mPackages) {
17533                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17534                        packageName, userId);
17535            }
17536        }
17537
17538        @Override
17539        public void setKeepUninstalledPackages(final List<String> packageList) {
17540            Preconditions.checkNotNull(packageList);
17541            List<String> removedFromList = null;
17542            synchronized (mPackages) {
17543                if (mKeepUninstalledPackages != null) {
17544                    final int packagesCount = mKeepUninstalledPackages.size();
17545                    for (int i = 0; i < packagesCount; i++) {
17546                        String oldPackage = mKeepUninstalledPackages.get(i);
17547                        if (packageList != null && packageList.contains(oldPackage)) {
17548                            continue;
17549                        }
17550                        if (removedFromList == null) {
17551                            removedFromList = new ArrayList<>();
17552                        }
17553                        removedFromList.add(oldPackage);
17554                    }
17555                }
17556                mKeepUninstalledPackages = new ArrayList<>(packageList);
17557                if (removedFromList != null) {
17558                    final int removedCount = removedFromList.size();
17559                    for (int i = 0; i < removedCount; i++) {
17560                        deletePackageIfUnusedLPr(removedFromList.get(i));
17561                    }
17562                }
17563            }
17564        }
17565
17566        @Override
17567        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17568            synchronized (mPackages) {
17569                // If we do not support permission review, done.
17570                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17571                    return false;
17572                }
17573
17574                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17575                if (packageSetting == null) {
17576                    return false;
17577                }
17578
17579                // Permission review applies only to apps not supporting the new permission model.
17580                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17581                    return false;
17582                }
17583
17584                // Legacy apps have the permission and get user consent on launch.
17585                PermissionsState permissionsState = packageSetting.getPermissionsState();
17586                return permissionsState.isPermissionReviewRequired(userId);
17587            }
17588        }
17589    }
17590
17591    @Override
17592    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17593        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17594        synchronized (mPackages) {
17595            final long identity = Binder.clearCallingIdentity();
17596            try {
17597                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17598                        packageNames, userId);
17599            } finally {
17600                Binder.restoreCallingIdentity(identity);
17601            }
17602        }
17603    }
17604
17605    private static void enforceSystemOrPhoneCaller(String tag) {
17606        int callingUid = Binder.getCallingUid();
17607        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17608            throw new SecurityException(
17609                    "Cannot call " + tag + " from UID " + callingUid);
17610        }
17611    }
17612}
17613