PackageManagerService.java revision e9fd1fa31ad6f62d1eb6f32cdcdab50349f246eb
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;
79import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
81import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
82import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
83import static com.android.internal.util.ArrayUtils.appendInt;
84import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
85import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
86import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
88import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
89import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
90import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
93
94import android.Manifest;
95import android.annotation.NonNull;
96import android.annotation.Nullable;
97import android.app.ActivityManager;
98import android.app.ActivityManagerNative;
99import android.app.AppGlobals;
100import android.app.IActivityManager;
101import android.app.admin.IDevicePolicyManager;
102import android.app.backup.IBackupManager;
103import android.content.BroadcastReceiver;
104import android.content.ComponentName;
105import android.content.Context;
106import android.content.IIntentReceiver;
107import android.content.Intent;
108import android.content.IntentFilter;
109import android.content.IntentSender;
110import android.content.IntentSender.SendIntentException;
111import android.content.ServiceConnection;
112import android.content.pm.ActivityInfo;
113import android.content.pm.ApplicationInfo;
114import android.content.pm.AppsQueryHelper;
115import android.content.pm.ComponentInfo;
116import android.content.pm.EphemeralApplicationInfo;
117import android.content.pm.EphemeralResolveInfo;
118import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
119import android.content.pm.FeatureInfo;
120import android.content.pm.IOnPermissionsChangeListener;
121import android.content.pm.IPackageDataObserver;
122import android.content.pm.IPackageDeleteObserver;
123import android.content.pm.IPackageDeleteObserver2;
124import android.content.pm.IPackageInstallObserver2;
125import android.content.pm.IPackageInstaller;
126import android.content.pm.IPackageManager;
127import android.content.pm.IPackageMoveObserver;
128import android.content.pm.IPackageStatsObserver;
129import android.content.pm.InstrumentationInfo;
130import android.content.pm.IntentFilterVerificationInfo;
131import android.content.pm.KeySet;
132import android.content.pm.PackageCleanItem;
133import android.content.pm.PackageInfo;
134import android.content.pm.PackageInfoLite;
135import android.content.pm.PackageInstaller;
136import android.content.pm.PackageManager;
137import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
138import android.content.pm.PackageManagerInternal;
139import android.content.pm.PackageParser;
140import android.content.pm.PackageParser.ActivityIntentInfo;
141import android.content.pm.PackageParser.PackageLite;
142import android.content.pm.PackageParser.PackageParserException;
143import android.content.pm.PackageStats;
144import android.content.pm.PackageUserState;
145import android.content.pm.ParceledListSlice;
146import android.content.pm.PermissionGroupInfo;
147import android.content.pm.PermissionInfo;
148import android.content.pm.ProviderInfo;
149import android.content.pm.ResolveInfo;
150import android.content.pm.ServiceInfo;
151import android.content.pm.Signature;
152import android.content.pm.UserInfo;
153import android.content.pm.VerificationParams;
154import android.content.pm.VerifierDeviceIdentity;
155import android.content.pm.VerifierInfo;
156import android.content.res.Resources;
157import android.graphics.Bitmap;
158import android.hardware.display.DisplayManager;
159import android.net.Uri;
160import android.os.Binder;
161import android.os.Build;
162import android.os.Bundle;
163import android.os.Debug;
164import android.os.Environment;
165import android.os.Environment.UserEnvironment;
166import android.os.FileUtils;
167import android.os.Handler;
168import android.os.IBinder;
169import android.os.Looper;
170import android.os.Message;
171import android.os.Parcel;
172import android.os.ParcelFileDescriptor;
173import android.os.Process;
174import android.os.RemoteCallbackList;
175import android.os.RemoteException;
176import android.os.ResultReceiver;
177import android.os.SELinux;
178import android.os.ServiceManager;
179import android.os.SystemClock;
180import android.os.SystemProperties;
181import android.os.Trace;
182import android.os.UserHandle;
183import android.os.UserManager;
184import android.os.storage.IMountService;
185import android.os.storage.MountServiceInternal;
186import android.os.storage.StorageEventListener;
187import android.os.storage.StorageManager;
188import android.os.storage.VolumeInfo;
189import android.os.storage.VolumeRecord;
190import android.security.KeyStore;
191import android.security.SystemKeyStore;
192import android.system.ErrnoException;
193import android.system.Os;
194import android.system.StructStat;
195import android.text.TextUtils;
196import android.text.format.DateUtils;
197import android.util.ArrayMap;
198import android.util.ArraySet;
199import android.util.AtomicFile;
200import android.util.DisplayMetrics;
201import android.util.EventLog;
202import android.util.ExceptionUtils;
203import android.util.Log;
204import android.util.LogPrinter;
205import android.util.MathUtils;
206import android.util.PrintStreamPrinter;
207import android.util.Slog;
208import android.util.SparseArray;
209import android.util.SparseBooleanArray;
210import android.util.SparseIntArray;
211import android.util.Xml;
212import android.view.Display;
213
214import com.android.internal.R;
215import com.android.internal.annotations.GuardedBy;
216import com.android.internal.app.IMediaContainerService;
217import com.android.internal.app.ResolverActivity;
218import com.android.internal.content.NativeLibraryHelper;
219import com.android.internal.content.PackageHelper;
220import com.android.internal.os.IParcelFileDescriptorFactory;
221import com.android.internal.os.InstallerConnection.InstallerException;
222import com.android.internal.os.SomeArgs;
223import com.android.internal.os.Zygote;
224import com.android.internal.util.ArrayUtils;
225import com.android.internal.util.FastPrintWriter;
226import com.android.internal.util.FastXmlSerializer;
227import com.android.internal.util.IndentingPrintWriter;
228import com.android.internal.util.Preconditions;
229import com.android.internal.util.XmlUtils;
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    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
982    private static final String TAG_ALL_GRANTS = "rt-grants";
983    private static final String TAG_GRANT = "grant";
984    private static final String ATTR_PACKAGE_NAME = "pkg";
985
986    private static final String TAG_PERMISSION = "perm";
987    private static final String ATTR_PERMISSION_NAME = "name";
988    private static final String ATTR_IS_GRANTED = "g";
989    private static final String ATTR_USER_SET = "set";
990    private static final String ATTR_USER_FIXED = "fixed";
991    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
992
993    // System/policy permission grants are not backed up
994    private static final int SYSTEM_RUNTIME_GRANT_MASK =
995            FLAG_PERMISSION_POLICY_FIXED
996            | FLAG_PERMISSION_SYSTEM_FIXED
997            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
998
999    // And we back up these user-adjusted states
1000    private static final int USER_RUNTIME_GRANT_MASK =
1001            FLAG_PERMISSION_USER_SET
1002            | FLAG_PERMISSION_USER_FIXED
1003            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1004
1005    final @Nullable String mRequiredVerifierPackage;
1006    final @Nullable String mRequiredInstallerPackage;
1007
1008    private final PackageUsage mPackageUsage = new PackageUsage();
1009
1010    private class PackageUsage {
1011        private static final int WRITE_INTERVAL
1012            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1013
1014        private final Object mFileLock = new Object();
1015        private final AtomicLong mLastWritten = new AtomicLong(0);
1016        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1017
1018        private boolean mIsHistoricalPackageUsageAvailable = true;
1019
1020        boolean isHistoricalPackageUsageAvailable() {
1021            return mIsHistoricalPackageUsageAvailable;
1022        }
1023
1024        void write(boolean force) {
1025            if (force) {
1026                writeInternal();
1027                return;
1028            }
1029            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1030                && !DEBUG_DEXOPT) {
1031                return;
1032            }
1033            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1034                new Thread("PackageUsage_DiskWriter") {
1035                    @Override
1036                    public void run() {
1037                        try {
1038                            writeInternal();
1039                        } finally {
1040                            mBackgroundWriteRunning.set(false);
1041                        }
1042                    }
1043                }.start();
1044            }
1045        }
1046
1047        private void writeInternal() {
1048            synchronized (mPackages) {
1049                synchronized (mFileLock) {
1050                    AtomicFile file = getFile();
1051                    FileOutputStream f = null;
1052                    try {
1053                        f = file.startWrite();
1054                        BufferedOutputStream out = new BufferedOutputStream(f);
1055                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1056                        StringBuilder sb = new StringBuilder();
1057                        for (PackageParser.Package pkg : mPackages.values()) {
1058                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1059                                continue;
1060                            }
1061                            sb.setLength(0);
1062                            sb.append(pkg.packageName);
1063                            sb.append(' ');
1064                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1065                            sb.append('\n');
1066                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1067                        }
1068                        out.flush();
1069                        file.finishWrite(f);
1070                    } catch (IOException e) {
1071                        if (f != null) {
1072                            file.failWrite(f);
1073                        }
1074                        Log.e(TAG, "Failed to write package usage times", e);
1075                    }
1076                }
1077            }
1078            mLastWritten.set(SystemClock.elapsedRealtime());
1079        }
1080
1081        void readLP() {
1082            synchronized (mFileLock) {
1083                AtomicFile file = getFile();
1084                BufferedInputStream in = null;
1085                try {
1086                    in = new BufferedInputStream(file.openRead());
1087                    StringBuffer sb = new StringBuffer();
1088                    while (true) {
1089                        String packageName = readToken(in, sb, ' ');
1090                        if (packageName == null) {
1091                            break;
1092                        }
1093                        String timeInMillisString = readToken(in, sb, '\n');
1094                        if (timeInMillisString == null) {
1095                            throw new IOException("Failed to find last usage time for package "
1096                                                  + packageName);
1097                        }
1098                        PackageParser.Package pkg = mPackages.get(packageName);
1099                        if (pkg == null) {
1100                            continue;
1101                        }
1102                        long timeInMillis;
1103                        try {
1104                            timeInMillis = Long.parseLong(timeInMillisString);
1105                        } catch (NumberFormatException e) {
1106                            throw new IOException("Failed to parse " + timeInMillisString
1107                                                  + " as a long.", e);
1108                        }
1109                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1110                    }
1111                } catch (FileNotFoundException expected) {
1112                    mIsHistoricalPackageUsageAvailable = false;
1113                } catch (IOException e) {
1114                    Log.w(TAG, "Failed to read package usage times", e);
1115                } finally {
1116                    IoUtils.closeQuietly(in);
1117                }
1118            }
1119            mLastWritten.set(SystemClock.elapsedRealtime());
1120        }
1121
1122        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1123                throws IOException {
1124            sb.setLength(0);
1125            while (true) {
1126                int ch = in.read();
1127                if (ch == -1) {
1128                    if (sb.length() == 0) {
1129                        return null;
1130                    }
1131                    throw new IOException("Unexpected EOF");
1132                }
1133                if (ch == endOfToken) {
1134                    return sb.toString();
1135                }
1136                sb.append((char)ch);
1137            }
1138        }
1139
1140        private AtomicFile getFile() {
1141            File dataDir = Environment.getDataDirectory();
1142            File systemDir = new File(dataDir, "system");
1143            File fname = new File(systemDir, "package-usage.list");
1144            return new AtomicFile(fname);
1145        }
1146    }
1147
1148    class PackageHandler extends Handler {
1149        private boolean mBound = false;
1150        final ArrayList<HandlerParams> mPendingInstalls =
1151            new ArrayList<HandlerParams>();
1152
1153        private boolean connectToService() {
1154            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1155                    " DefaultContainerService");
1156            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1157            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1158            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1159                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1160                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1161                mBound = true;
1162                return true;
1163            }
1164            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1165            return false;
1166        }
1167
1168        private void disconnectService() {
1169            mContainerService = null;
1170            mBound = false;
1171            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1172            mContext.unbindService(mDefContainerConn);
1173            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1174        }
1175
1176        PackageHandler(Looper looper) {
1177            super(looper);
1178        }
1179
1180        public void handleMessage(Message msg) {
1181            try {
1182                doHandleMessage(msg);
1183            } finally {
1184                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1185            }
1186        }
1187
1188        void doHandleMessage(Message msg) {
1189            switch (msg.what) {
1190                case INIT_COPY: {
1191                    HandlerParams params = (HandlerParams) msg.obj;
1192                    int idx = mPendingInstalls.size();
1193                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1194                    // If a bind was already initiated we dont really
1195                    // need to do anything. The pending install
1196                    // will be processed later on.
1197                    if (!mBound) {
1198                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1199                                System.identityHashCode(mHandler));
1200                        // If this is the only one pending we might
1201                        // have to bind to the service again.
1202                        if (!connectToService()) {
1203                            Slog.e(TAG, "Failed to bind to media container service");
1204                            params.serviceError();
1205                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1206                                    System.identityHashCode(mHandler));
1207                            if (params.traceMethod != null) {
1208                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1209                                        params.traceCookie);
1210                            }
1211                            return;
1212                        } else {
1213                            // Once we bind to the service, the first
1214                            // pending request will be processed.
1215                            mPendingInstalls.add(idx, params);
1216                        }
1217                    } else {
1218                        mPendingInstalls.add(idx, params);
1219                        // Already bound to the service. Just make
1220                        // sure we trigger off processing the first request.
1221                        if (idx == 0) {
1222                            mHandler.sendEmptyMessage(MCS_BOUND);
1223                        }
1224                    }
1225                    break;
1226                }
1227                case MCS_BOUND: {
1228                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1229                    if (msg.obj != null) {
1230                        mContainerService = (IMediaContainerService) msg.obj;
1231                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1232                                System.identityHashCode(mHandler));
1233                    }
1234                    if (mContainerService == null) {
1235                        if (!mBound) {
1236                            // Something seriously wrong since we are not bound and we are not
1237                            // waiting for connection. Bail out.
1238                            Slog.e(TAG, "Cannot bind to media container service");
1239                            for (HandlerParams params : mPendingInstalls) {
1240                                // Indicate service bind error
1241                                params.serviceError();
1242                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1243                                        System.identityHashCode(params));
1244                                if (params.traceMethod != null) {
1245                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1246                                            params.traceMethod, params.traceCookie);
1247                                }
1248                                return;
1249                            }
1250                            mPendingInstalls.clear();
1251                        } else {
1252                            Slog.w(TAG, "Waiting to connect to media container service");
1253                        }
1254                    } else if (mPendingInstalls.size() > 0) {
1255                        HandlerParams params = mPendingInstalls.get(0);
1256                        if (params != null) {
1257                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1258                                    System.identityHashCode(params));
1259                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1260                            if (params.startCopy()) {
1261                                // We are done...  look for more work or to
1262                                // go idle.
1263                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1264                                        "Checking for more work or unbind...");
1265                                // Delete pending install
1266                                if (mPendingInstalls.size() > 0) {
1267                                    mPendingInstalls.remove(0);
1268                                }
1269                                if (mPendingInstalls.size() == 0) {
1270                                    if (mBound) {
1271                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1272                                                "Posting delayed MCS_UNBIND");
1273                                        removeMessages(MCS_UNBIND);
1274                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1275                                        // Unbind after a little delay, to avoid
1276                                        // continual thrashing.
1277                                        sendMessageDelayed(ubmsg, 10000);
1278                                    }
1279                                } else {
1280                                    // There are more pending requests in queue.
1281                                    // Just post MCS_BOUND message to trigger processing
1282                                    // of next pending install.
1283                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1284                                            "Posting MCS_BOUND for next work");
1285                                    mHandler.sendEmptyMessage(MCS_BOUND);
1286                                }
1287                            }
1288                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1289                        }
1290                    } else {
1291                        // Should never happen ideally.
1292                        Slog.w(TAG, "Empty queue");
1293                    }
1294                    break;
1295                }
1296                case MCS_RECONNECT: {
1297                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1298                    if (mPendingInstalls.size() > 0) {
1299                        if (mBound) {
1300                            disconnectService();
1301                        }
1302                        if (!connectToService()) {
1303                            Slog.e(TAG, "Failed to bind to media container service");
1304                            for (HandlerParams params : mPendingInstalls) {
1305                                // Indicate service bind error
1306                                params.serviceError();
1307                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1308                                        System.identityHashCode(params));
1309                            }
1310                            mPendingInstalls.clear();
1311                        }
1312                    }
1313                    break;
1314                }
1315                case MCS_UNBIND: {
1316                    // If there is no actual work left, then time to unbind.
1317                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1318
1319                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1320                        if (mBound) {
1321                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1322
1323                            disconnectService();
1324                        }
1325                    } else if (mPendingInstalls.size() > 0) {
1326                        // There are more pending requests in queue.
1327                        // Just post MCS_BOUND message to trigger processing
1328                        // of next pending install.
1329                        mHandler.sendEmptyMessage(MCS_BOUND);
1330                    }
1331
1332                    break;
1333                }
1334                case MCS_GIVE_UP: {
1335                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1336                    HandlerParams params = mPendingInstalls.remove(0);
1337                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1338                            System.identityHashCode(params));
1339                    break;
1340                }
1341                case SEND_PENDING_BROADCAST: {
1342                    String packages[];
1343                    ArrayList<String> components[];
1344                    int size = 0;
1345                    int uids[];
1346                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1347                    synchronized (mPackages) {
1348                        if (mPendingBroadcasts == null) {
1349                            return;
1350                        }
1351                        size = mPendingBroadcasts.size();
1352                        if (size <= 0) {
1353                            // Nothing to be done. Just return
1354                            return;
1355                        }
1356                        packages = new String[size];
1357                        components = new ArrayList[size];
1358                        uids = new int[size];
1359                        int i = 0;  // filling out the above arrays
1360
1361                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1362                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1363                            Iterator<Map.Entry<String, ArrayList<String>>> it
1364                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1365                                            .entrySet().iterator();
1366                            while (it.hasNext() && i < size) {
1367                                Map.Entry<String, ArrayList<String>> ent = it.next();
1368                                packages[i] = ent.getKey();
1369                                components[i] = ent.getValue();
1370                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1371                                uids[i] = (ps != null)
1372                                        ? UserHandle.getUid(packageUserId, ps.appId)
1373                                        : -1;
1374                                i++;
1375                            }
1376                        }
1377                        size = i;
1378                        mPendingBroadcasts.clear();
1379                    }
1380                    // Send broadcasts
1381                    for (int i = 0; i < size; i++) {
1382                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1383                    }
1384                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1385                    break;
1386                }
1387                case START_CLEANING_PACKAGE: {
1388                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1389                    final String packageName = (String)msg.obj;
1390                    final int userId = msg.arg1;
1391                    final boolean andCode = msg.arg2 != 0;
1392                    synchronized (mPackages) {
1393                        if (userId == UserHandle.USER_ALL) {
1394                            int[] users = sUserManager.getUserIds();
1395                            for (int user : users) {
1396                                mSettings.addPackageToCleanLPw(
1397                                        new PackageCleanItem(user, packageName, andCode));
1398                            }
1399                        } else {
1400                            mSettings.addPackageToCleanLPw(
1401                                    new PackageCleanItem(userId, packageName, andCode));
1402                        }
1403                    }
1404                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1405                    startCleaningPackages();
1406                } break;
1407                case POST_INSTALL: {
1408                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1409
1410                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1411                    mRunningInstalls.delete(msg.arg1);
1412                    boolean deleteOld = false;
1413
1414                    if (data != null) {
1415                        InstallArgs args = data.args;
1416                        PackageInstalledInfo res = data.res;
1417
1418                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1419                            final String packageName = res.pkg.applicationInfo.packageName;
1420                            res.removedInfo.sendBroadcast(false, true, false);
1421                            Bundle extras = new Bundle(1);
1422                            extras.putInt(Intent.EXTRA_UID, res.uid);
1423
1424                            // Now that we successfully installed the package, grant runtime
1425                            // permissions if requested before broadcasting the install.
1426                            if ((args.installFlags
1427                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1428                                    && res.pkg.applicationInfo.targetSdkVersion
1429                                            >= Build.VERSION_CODES.M) {
1430                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1431                                        args.installGrantPermissions);
1432                            }
1433
1434                            synchronized (mPackages) {
1435                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1436                            }
1437
1438                            // Determine the set of users who are adding this
1439                            // package for the first time vs. those who are seeing
1440                            // an update.
1441                            int[] firstUsers;
1442                            int[] updateUsers = new int[0];
1443                            if (res.origUsers == null || res.origUsers.length == 0) {
1444                                firstUsers = res.newUsers;
1445                            } else {
1446                                firstUsers = new int[0];
1447                                for (int i=0; i<res.newUsers.length; i++) {
1448                                    int user = res.newUsers[i];
1449                                    boolean isNew = true;
1450                                    for (int j=0; j<res.origUsers.length; j++) {
1451                                        if (res.origUsers[j] == user) {
1452                                            isNew = false;
1453                                            break;
1454                                        }
1455                                    }
1456                                    if (isNew) {
1457                                        int[] newFirst = new int[firstUsers.length+1];
1458                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1459                                                firstUsers.length);
1460                                        newFirst[firstUsers.length] = user;
1461                                        firstUsers = newFirst;
1462                                    } else {
1463                                        int[] newUpdate = new int[updateUsers.length+1];
1464                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1465                                                updateUsers.length);
1466                                        newUpdate[updateUsers.length] = user;
1467                                        updateUsers = newUpdate;
1468                                    }
1469                                }
1470                            }
1471                            // don't broadcast for ephemeral installs/updates
1472                            final boolean isEphemeral = isEphemeral(res.pkg);
1473                            if (!isEphemeral) {
1474                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1475                                        extras, 0 /*flags*/, null /*targetPackage*/,
1476                                        null /*finishedReceiver*/, firstUsers);
1477                            }
1478                            final boolean update = res.removedInfo.removedPackage != null;
1479                            if (update) {
1480                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1481                            }
1482                            if (!isEphemeral) {
1483                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1484                                        extras, 0 /*flags*/, null /*targetPackage*/,
1485                                        null /*finishedReceiver*/, updateUsers);
1486                            }
1487                            if (update) {
1488                                if (!isEphemeral) {
1489                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1490                                            packageName, extras, 0 /*flags*/,
1491                                            null /*targetPackage*/, null /*finishedReceiver*/,
1492                                            updateUsers);
1493                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1494                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1495                                            packageName /*targetPackage*/,
1496                                            null /*finishedReceiver*/, updateUsers);
1497                                }
1498
1499                                // treat asec-hosted packages like removable media on upgrade
1500                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1501                                    if (DEBUG_INSTALL) {
1502                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1503                                                + " is ASEC-hosted -> AVAILABLE");
1504                                    }
1505                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1506                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1507                                    pkgList.add(packageName);
1508                                    sendResourcesChangedBroadcast(true, true,
1509                                            pkgList,uidArray, null);
1510                                }
1511                            }
1512                            if (res.removedInfo.args != null) {
1513                                // Remove the replaced package's older resources safely now
1514                                deleteOld = true;
1515                            }
1516
1517
1518                            // Work that needs to happen on first install within each user
1519                            if (firstUsers.length > 0) {
1520                                for (int userId : firstUsers) {
1521                                    synchronized (mPackages) {
1522                                        // If this app is a browser and it's newly-installed for
1523                                        // some users, clear any default-browser state in those
1524                                        // users.  The app's nature doesn't depend on the user,
1525                                        // so we can just check its browser nature in any user
1526                                        // and generalize.
1527                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1528                                            mSettings.setDefaultBrowserPackageNameLPw(
1529                                                    null, userId);
1530                                        }
1531
1532                                        // We may also need to apply pending (restored) runtime
1533                                        // permission grants within these users.
1534                                        mSettings.applyPendingPermissionGrantsLPw(
1535                                                packageName, userId);
1536                                    }
1537                                }
1538                            }
1539                            // Log current value of "unknown sources" setting
1540                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1541                                getUnknownSourcesSettings());
1542                        }
1543                        // Force a gc to clear up things
1544                        Runtime.getRuntime().gc();
1545                        // We delete after a gc for applications  on sdcard.
1546                        if (deleteOld) {
1547                            synchronized (mInstallLock) {
1548                                res.removedInfo.args.doPostDeleteLI(true);
1549                            }
1550                        }
1551                        if (args.observer != null) {
1552                            try {
1553                                Bundle extras = extrasForInstallResult(res);
1554                                args.observer.onPackageInstalled(res.name, res.returnCode,
1555                                        res.returnMsg, extras);
1556                            } catch (RemoteException e) {
1557                                Slog.i(TAG, "Observer no longer exists.");
1558                            }
1559                        }
1560                        if (args.traceMethod != null) {
1561                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1562                                    args.traceCookie);
1563                        }
1564                        return;
1565                    } else {
1566                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1567                    }
1568
1569                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1570                } break;
1571                case UPDATED_MEDIA_STATUS: {
1572                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1573                    boolean reportStatus = msg.arg1 == 1;
1574                    boolean doGc = msg.arg2 == 1;
1575                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1576                    if (doGc) {
1577                        // Force a gc to clear up stale containers.
1578                        Runtime.getRuntime().gc();
1579                    }
1580                    if (msg.obj != null) {
1581                        @SuppressWarnings("unchecked")
1582                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1583                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1584                        // Unload containers
1585                        unloadAllContainers(args);
1586                    }
1587                    if (reportStatus) {
1588                        try {
1589                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1590                            PackageHelper.getMountService().finishMediaUpdate();
1591                        } catch (RemoteException e) {
1592                            Log.e(TAG, "MountService not running?");
1593                        }
1594                    }
1595                } break;
1596                case WRITE_SETTINGS: {
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        removeMessages(WRITE_SETTINGS);
1600                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1601                        mSettings.writeLPr();
1602                        mDirtyUsers.clear();
1603                    }
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1605                } break;
1606                case WRITE_PACKAGE_RESTRICTIONS: {
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1608                    synchronized (mPackages) {
1609                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1610                        for (int userId : mDirtyUsers) {
1611                            mSettings.writePackageRestrictionsLPr(userId);
1612                        }
1613                        mDirtyUsers.clear();
1614                    }
1615                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1616                } break;
1617                case CHECK_PENDING_VERIFICATION: {
1618                    final int verificationId = msg.arg1;
1619                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1620
1621                    if ((state != null) && !state.timeoutExtended()) {
1622                        final InstallArgs args = state.getInstallArgs();
1623                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1624
1625                        Slog.i(TAG, "Verification timed out for " + originUri);
1626                        mPendingVerification.remove(verificationId);
1627
1628                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1629
1630                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1631                            Slog.i(TAG, "Continuing with installation of " + originUri);
1632                            state.setVerifierResponse(Binder.getCallingUid(),
1633                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1634                            broadcastPackageVerified(verificationId, originUri,
1635                                    PackageManager.VERIFICATION_ALLOW,
1636                                    state.getInstallArgs().getUser());
1637                            try {
1638                                ret = args.copyApk(mContainerService, true);
1639                            } catch (RemoteException e) {
1640                                Slog.e(TAG, "Could not contact the ContainerService");
1641                            }
1642                        } else {
1643                            broadcastPackageVerified(verificationId, originUri,
1644                                    PackageManager.VERIFICATION_REJECT,
1645                                    state.getInstallArgs().getUser());
1646                        }
1647
1648                        Trace.asyncTraceEnd(
1649                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1650
1651                        processPendingInstall(args, ret);
1652                        mHandler.sendEmptyMessage(MCS_UNBIND);
1653                    }
1654                    break;
1655                }
1656                case PACKAGE_VERIFIED: {
1657                    final int verificationId = msg.arg1;
1658
1659                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1660                    if (state == null) {
1661                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1662                        break;
1663                    }
1664
1665                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1666
1667                    state.setVerifierResponse(response.callerUid, response.code);
1668
1669                    if (state.isVerificationComplete()) {
1670                        mPendingVerification.remove(verificationId);
1671
1672                        final InstallArgs args = state.getInstallArgs();
1673                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1674
1675                        int ret;
1676                        if (state.isInstallAllowed()) {
1677                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1678                            broadcastPackageVerified(verificationId, originUri,
1679                                    response.code, state.getInstallArgs().getUser());
1680                            try {
1681                                ret = args.copyApk(mContainerService, true);
1682                            } catch (RemoteException e) {
1683                                Slog.e(TAG, "Could not contact the ContainerService");
1684                            }
1685                        } else {
1686                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1687                        }
1688
1689                        Trace.asyncTraceEnd(
1690                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1691
1692                        processPendingInstall(args, ret);
1693                        mHandler.sendEmptyMessage(MCS_UNBIND);
1694                    }
1695
1696                    break;
1697                }
1698                case START_INTENT_FILTER_VERIFICATIONS: {
1699                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1700                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1701                            params.replacing, params.pkg);
1702                    break;
1703                }
1704                case INTENT_FILTER_VERIFIED: {
1705                    final int verificationId = msg.arg1;
1706
1707                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1708                            verificationId);
1709                    if (state == null) {
1710                        Slog.w(TAG, "Invalid IntentFilter verification token "
1711                                + verificationId + " received");
1712                        break;
1713                    }
1714
1715                    final int userId = state.getUserId();
1716
1717                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1718                            "Processing IntentFilter verification with token:"
1719                            + verificationId + " and userId:" + userId);
1720
1721                    final IntentFilterVerificationResponse response =
1722                            (IntentFilterVerificationResponse) msg.obj;
1723
1724                    state.setVerifierResponse(response.callerUid, response.code);
1725
1726                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1727                            "IntentFilter verification with token:" + verificationId
1728                            + " and userId:" + userId
1729                            + " is settings verifier response with response code:"
1730                            + response.code);
1731
1732                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1733                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1734                                + response.getFailedDomainsString());
1735                    }
1736
1737                    if (state.isVerificationComplete()) {
1738                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1739                    } else {
1740                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1741                                "IntentFilter verification with token:" + verificationId
1742                                + " was not said to be complete");
1743                    }
1744
1745                    break;
1746                }
1747            }
1748        }
1749    }
1750
1751    private StorageEventListener mStorageListener = new StorageEventListener() {
1752        @Override
1753        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1754            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1755                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1756                    final String volumeUuid = vol.getFsUuid();
1757
1758                    // Clean up any users or apps that were removed or recreated
1759                    // while this volume was missing
1760                    reconcileUsers(volumeUuid);
1761                    reconcileApps(volumeUuid);
1762
1763                    // Clean up any install sessions that expired or were
1764                    // cancelled while this volume was missing
1765                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1766
1767                    loadPrivatePackages(vol);
1768
1769                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1770                    unloadPrivatePackages(vol);
1771                }
1772            }
1773
1774            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1775                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1776                    updateExternalMediaStatus(true, false);
1777                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1778                    updateExternalMediaStatus(false, false);
1779                }
1780            }
1781        }
1782
1783        @Override
1784        public void onVolumeForgotten(String fsUuid) {
1785            if (TextUtils.isEmpty(fsUuid)) {
1786                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1787                return;
1788            }
1789
1790            // Remove any apps installed on the forgotten volume
1791            synchronized (mPackages) {
1792                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1793                for (PackageSetting ps : packages) {
1794                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1795                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1796                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1797                }
1798
1799                mSettings.onVolumeForgotten(fsUuid);
1800                mSettings.writeLPr();
1801            }
1802        }
1803    };
1804
1805    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1806            String[] grantedPermissions) {
1807        if (userId >= UserHandle.USER_SYSTEM) {
1808            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1809        } else if (userId == UserHandle.USER_ALL) {
1810            final int[] userIds;
1811            synchronized (mPackages) {
1812                userIds = UserManagerService.getInstance().getUserIds();
1813            }
1814            for (int someUserId : userIds) {
1815                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1816            }
1817        }
1818
1819        // We could have touched GID membership, so flush out packages.list
1820        synchronized (mPackages) {
1821            mSettings.writePackageListLPr();
1822        }
1823    }
1824
1825    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1826            String[] grantedPermissions) {
1827        SettingBase sb = (SettingBase) pkg.mExtras;
1828        if (sb == null) {
1829            return;
1830        }
1831
1832        PermissionsState permissionsState = sb.getPermissionsState();
1833
1834        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1835                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1836
1837        synchronized (mPackages) {
1838            for (String permission : pkg.requestedPermissions) {
1839                BasePermission bp = mSettings.mPermissions.get(permission);
1840                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1841                        && (grantedPermissions == null
1842                               || ArrayUtils.contains(grantedPermissions, permission))) {
1843                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1844                    // Installer cannot change immutable permissions.
1845                    if ((flags & immutableFlags) == 0) {
1846                        grantRuntimePermission(pkg.packageName, permission, userId);
1847                    }
1848                }
1849            }
1850        }
1851    }
1852
1853    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1854        Bundle extras = null;
1855        switch (res.returnCode) {
1856            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1857                extras = new Bundle();
1858                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1859                        res.origPermission);
1860                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1861                        res.origPackage);
1862                break;
1863            }
1864            case PackageManager.INSTALL_SUCCEEDED: {
1865                extras = new Bundle();
1866                extras.putBoolean(Intent.EXTRA_REPLACING,
1867                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1868                break;
1869            }
1870        }
1871        return extras;
1872    }
1873
1874    void scheduleWriteSettingsLocked() {
1875        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1876            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1877        }
1878    }
1879
1880    void scheduleWritePackageRestrictionsLocked(int userId) {
1881        if (!sUserManager.exists(userId)) return;
1882        mDirtyUsers.add(userId);
1883        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1884            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1885        }
1886    }
1887
1888    public static PackageManagerService main(Context context, Installer installer,
1889            boolean factoryTest, boolean onlyCore) {
1890        PackageManagerService m = new PackageManagerService(context, installer,
1891                factoryTest, onlyCore);
1892        m.enableSystemUserPackages();
1893        ServiceManager.addService("package", m);
1894        return m;
1895    }
1896
1897    private void enableSystemUserPackages() {
1898        if (!UserManager.isSplitSystemUser()) {
1899            return;
1900        }
1901        // For system user, enable apps based on the following conditions:
1902        // - app is whitelisted or belong to one of these groups:
1903        //   -- system app which has no launcher icons
1904        //   -- system app which has INTERACT_ACROSS_USERS permission
1905        //   -- system IME app
1906        // - app is not in the blacklist
1907        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1908        Set<String> enableApps = new ArraySet<>();
1909        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1910                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1911                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1912        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1913        enableApps.addAll(wlApps);
1914        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1915                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1916        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1917        enableApps.removeAll(blApps);
1918        Log.i(TAG, "Applications installed for system user: " + enableApps);
1919        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1920                UserHandle.SYSTEM);
1921        final int allAppsSize = allAps.size();
1922        synchronized (mPackages) {
1923            for (int i = 0; i < allAppsSize; i++) {
1924                String pName = allAps.get(i);
1925                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1926                // Should not happen, but we shouldn't be failing if it does
1927                if (pkgSetting == null) {
1928                    continue;
1929                }
1930                boolean install = enableApps.contains(pName);
1931                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1932                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1933                            + " for system user");
1934                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1935                }
1936            }
1937        }
1938    }
1939
1940    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1941        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1942                Context.DISPLAY_SERVICE);
1943        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1944    }
1945
1946    public PackageManagerService(Context context, Installer installer,
1947            boolean factoryTest, boolean onlyCore) {
1948        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1949                SystemClock.uptimeMillis());
1950
1951        if (mSdkVersion <= 0) {
1952            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1953        }
1954
1955        mContext = context;
1956        mFactoryTest = factoryTest;
1957        mOnlyCore = onlyCore;
1958        mMetrics = new DisplayMetrics();
1959        mSettings = new Settings(mPackages);
1960        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1961                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1962        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1963                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1964        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1965                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1966        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1967                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1968        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1969                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1970        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1971                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1972
1973        String separateProcesses = SystemProperties.get("debug.separate_processes");
1974        if (separateProcesses != null && separateProcesses.length() > 0) {
1975            if ("*".equals(separateProcesses)) {
1976                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1977                mSeparateProcesses = null;
1978                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1979            } else {
1980                mDefParseFlags = 0;
1981                mSeparateProcesses = separateProcesses.split(",");
1982                Slog.w(TAG, "Running with debug.separate_processes: "
1983                        + separateProcesses);
1984            }
1985        } else {
1986            mDefParseFlags = 0;
1987            mSeparateProcesses = null;
1988        }
1989
1990        mInstaller = installer;
1991        mPackageDexOptimizer = new PackageDexOptimizer(this);
1992        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1993
1994        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1995                FgThread.get().getLooper());
1996
1997        getDefaultDisplayMetrics(context, mMetrics);
1998
1999        SystemConfig systemConfig = SystemConfig.getInstance();
2000        mGlobalGids = systemConfig.getGlobalGids();
2001        mSystemPermissions = systemConfig.getSystemPermissions();
2002        mAvailableFeatures = systemConfig.getAvailableFeatures();
2003
2004        synchronized (mInstallLock) {
2005        // writer
2006        synchronized (mPackages) {
2007            mHandlerThread = new ServiceThread(TAG,
2008                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2009            mHandlerThread.start();
2010            mHandler = new PackageHandler(mHandlerThread.getLooper());
2011            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2012
2013            File dataDir = Environment.getDataDirectory();
2014            mAppInstallDir = new File(dataDir, "app");
2015            mAppLib32InstallDir = new File(dataDir, "app-lib");
2016            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2017            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2018            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2019
2020            sUserManager = new UserManagerService(context, this, mPackages);
2021
2022            // Propagate permission configuration in to package manager.
2023            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2024                    = systemConfig.getPermissions();
2025            for (int i=0; i<permConfig.size(); i++) {
2026                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2027                BasePermission bp = mSettings.mPermissions.get(perm.name);
2028                if (bp == null) {
2029                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2030                    mSettings.mPermissions.put(perm.name, bp);
2031                }
2032                if (perm.gids != null) {
2033                    bp.setGids(perm.gids, perm.perUser);
2034                }
2035            }
2036
2037            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2038            for (int i=0; i<libConfig.size(); i++) {
2039                mSharedLibraries.put(libConfig.keyAt(i),
2040                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2041            }
2042
2043            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2044
2045            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2046
2047            String customResolverActivity = Resources.getSystem().getString(
2048                    R.string.config_customResolverActivity);
2049            if (TextUtils.isEmpty(customResolverActivity)) {
2050                customResolverActivity = null;
2051            } else {
2052                mCustomResolverComponentName = ComponentName.unflattenFromString(
2053                        customResolverActivity);
2054            }
2055
2056            long startTime = SystemClock.uptimeMillis();
2057
2058            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2059                    startTime);
2060
2061            // Set flag to monitor and not change apk file paths when
2062            // scanning install directories.
2063            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2064
2065            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2066            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2067
2068            if (bootClassPath == null) {
2069                Slog.w(TAG, "No BOOTCLASSPATH found!");
2070            }
2071
2072            if (systemServerClassPath == null) {
2073                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2074            }
2075
2076            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2077            final String[] dexCodeInstructionSets =
2078                    getDexCodeInstructionSets(
2079                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2080
2081            /**
2082             * Ensure all external libraries have had dexopt run on them.
2083             */
2084            if (mSharedLibraries.size() > 0) {
2085                // NOTE: For now, we're compiling these system "shared libraries"
2086                // (and framework jars) into all available architectures. It's possible
2087                // to compile them only when we come across an app that uses them (there's
2088                // already logic for that in scanPackageLI) but that adds some complexity.
2089                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2090                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2091                        final String lib = libEntry.path;
2092                        if (lib == null) {
2093                            continue;
2094                        }
2095
2096                        try {
2097                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2098                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2099                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2100                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2101                            }
2102                        } catch (FileNotFoundException e) {
2103                            Slog.w(TAG, "Library not found: " + lib);
2104                        } catch (IOException | InstallerException e) {
2105                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2106                                    + e.getMessage());
2107                        }
2108                    }
2109                }
2110            }
2111
2112            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2113
2114            final VersionInfo ver = mSettings.getInternalVersion();
2115            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2116            // when upgrading from pre-M, promote system app permissions from install to runtime
2117            mPromoteSystemApps =
2118                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2119
2120            // save off the names of pre-existing system packages prior to scanning; we don't
2121            // want to automatically grant runtime permissions for new system apps
2122            if (mPromoteSystemApps) {
2123                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2124                while (pkgSettingIter.hasNext()) {
2125                    PackageSetting ps = pkgSettingIter.next();
2126                    if (isSystemApp(ps)) {
2127                        mExistingSystemPackages.add(ps.name);
2128                    }
2129                }
2130            }
2131
2132            // Collect vendor overlay packages.
2133            // (Do this before scanning any apps.)
2134            // For security and version matching reason, only consider
2135            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2136            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2137            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2138                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2139
2140            // Find base frameworks (resource packages without code).
2141            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2142                    | PackageParser.PARSE_IS_SYSTEM_DIR
2143                    | PackageParser.PARSE_IS_PRIVILEGED,
2144                    scanFlags | SCAN_NO_DEX, 0);
2145
2146            // Collected privileged system packages.
2147            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2148            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2149                    | PackageParser.PARSE_IS_SYSTEM_DIR
2150                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2151
2152            // Collect ordinary system packages.
2153            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2154            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2155                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2156
2157            // Collect all vendor packages.
2158            File vendorAppDir = new File("/vendor/app");
2159            try {
2160                vendorAppDir = vendorAppDir.getCanonicalFile();
2161            } catch (IOException e) {
2162                // failed to look up canonical path, continue with original one
2163            }
2164            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2165                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2166
2167            // Collect all OEM packages.
2168            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2169            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2170                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2171
2172            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2173            try {
2174                mInstaller.moveFiles();
2175            } catch (InstallerException e) {
2176                logCriticalInfo(Log.WARN, "Update commands failed: " + e);
2177            }
2178
2179            // Prune any system packages that no longer exist.
2180            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2181            if (!mOnlyCore) {
2182                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2183                while (psit.hasNext()) {
2184                    PackageSetting ps = psit.next();
2185
2186                    /*
2187                     * If this is not a system app, it can't be a
2188                     * disable system app.
2189                     */
2190                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2191                        continue;
2192                    }
2193
2194                    /*
2195                     * If the package is scanned, it's not erased.
2196                     */
2197                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2198                    if (scannedPkg != null) {
2199                        /*
2200                         * If the system app is both scanned and in the
2201                         * disabled packages list, then it must have been
2202                         * added via OTA. Remove it from the currently
2203                         * scanned package so the previously user-installed
2204                         * application can be scanned.
2205                         */
2206                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2207                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2208                                    + ps.name + "; removing system app.  Last known codePath="
2209                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2210                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2211                                    + scannedPkg.mVersionCode);
2212                            removePackageLI(ps, true);
2213                            mExpectingBetter.put(ps.name, ps.codePath);
2214                        }
2215
2216                        continue;
2217                    }
2218
2219                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2220                        psit.remove();
2221                        logCriticalInfo(Log.WARN, "System package " + ps.name
2222                                + " no longer exists; wiping its data");
2223                        removeDataDirsLI(null, ps.name);
2224                    } else {
2225                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2226                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2227                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2228                        }
2229                    }
2230                }
2231            }
2232
2233            //look for any incomplete package installations
2234            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2235            //clean up list
2236            for(int i = 0; i < deletePkgsList.size(); i++) {
2237                //clean up here
2238                cleanupInstallFailedPackage(deletePkgsList.get(i));
2239            }
2240            //delete tmp files
2241            deleteTempPackageFiles();
2242
2243            // Remove any shared userIDs that have no associated packages
2244            mSettings.pruneSharedUsersLPw();
2245
2246            if (!mOnlyCore) {
2247                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2248                        SystemClock.uptimeMillis());
2249                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2250
2251                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2252                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2253
2254                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2255                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2256
2257                /**
2258                 * Remove disable package settings for any updated system
2259                 * apps that were removed via an OTA. If they're not a
2260                 * previously-updated app, remove them completely.
2261                 * Otherwise, just revoke their system-level permissions.
2262                 */
2263                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2264                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2265                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2266
2267                    String msg;
2268                    if (deletedPkg == null) {
2269                        msg = "Updated system package " + deletedAppName
2270                                + " no longer exists; wiping its data";
2271                        removeDataDirsLI(null, deletedAppName);
2272                    } else {
2273                        msg = "Updated system app + " + deletedAppName
2274                                + " no longer present; removing system privileges for "
2275                                + deletedAppName;
2276
2277                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2278
2279                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2280                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2281                    }
2282                    logCriticalInfo(Log.WARN, msg);
2283                }
2284
2285                /**
2286                 * Make sure all system apps that we expected to appear on
2287                 * the userdata partition actually showed up. If they never
2288                 * appeared, crawl back and revive the system version.
2289                 */
2290                for (int i = 0; i < mExpectingBetter.size(); i++) {
2291                    final String packageName = mExpectingBetter.keyAt(i);
2292                    if (!mPackages.containsKey(packageName)) {
2293                        final File scanFile = mExpectingBetter.valueAt(i);
2294
2295                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2296                                + " but never showed up; reverting to system");
2297
2298                        final int reparseFlags;
2299                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2300                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2301                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2302                                    | PackageParser.PARSE_IS_PRIVILEGED;
2303                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2304                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2305                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2306                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2307                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2308                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2309                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2310                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2311                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2312                        } else {
2313                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2314                            continue;
2315                        }
2316
2317                        mSettings.enableSystemPackageLPw(packageName);
2318
2319                        try {
2320                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2321                        } catch (PackageManagerException e) {
2322                            Slog.e(TAG, "Failed to parse original system package: "
2323                                    + e.getMessage());
2324                        }
2325                    }
2326                }
2327            }
2328            mExpectingBetter.clear();
2329
2330            // Now that we know all of the shared libraries, update all clients to have
2331            // the correct library paths.
2332            updateAllSharedLibrariesLPw();
2333
2334            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2335                // NOTE: We ignore potential failures here during a system scan (like
2336                // the rest of the commands above) because there's precious little we
2337                // can do about it. A settings error is reported, though.
2338                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2339                        false /* boot complete */);
2340            }
2341
2342            // Now that we know all the packages we are keeping,
2343            // read and update their last usage times.
2344            mPackageUsage.readLP();
2345
2346            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2347                    SystemClock.uptimeMillis());
2348            Slog.i(TAG, "Time to scan packages: "
2349                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2350                    + " seconds");
2351
2352            // If the platform SDK has changed since the last time we booted,
2353            // we need to re-grant app permission to catch any new ones that
2354            // appear.  This is really a hack, and means that apps can in some
2355            // cases get permissions that the user didn't initially explicitly
2356            // allow...  it would be nice to have some better way to handle
2357            // this situation.
2358            int updateFlags = UPDATE_PERMISSIONS_ALL;
2359            if (ver.sdkVersion != mSdkVersion) {
2360                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2361                        + mSdkVersion + "; regranting permissions for internal storage");
2362                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2363            }
2364            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2365            ver.sdkVersion = mSdkVersion;
2366
2367            // If this is the first boot or an update from pre-M, and it is a normal
2368            // boot, then we need to initialize the default preferred apps across
2369            // all defined users.
2370            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2371                for (UserInfo user : sUserManager.getUsers(true)) {
2372                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2373                    applyFactoryDefaultBrowserLPw(user.id);
2374                    primeDomainVerificationsLPw(user.id);
2375                }
2376            }
2377
2378            // If this is first boot after an OTA, and a normal boot, then
2379            // we need to clear code cache directories.
2380            if (mIsUpgrade && !onlyCore) {
2381                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2382                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2383                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2384                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2385                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2386                    }
2387                }
2388                ver.fingerprint = Build.FINGERPRINT;
2389            }
2390
2391            checkDefaultBrowser();
2392
2393            // clear only after permissions and other defaults have been updated
2394            mExistingSystemPackages.clear();
2395            mPromoteSystemApps = false;
2396
2397            // All the changes are done during package scanning.
2398            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2399
2400            // can downgrade to reader
2401            mSettings.writeLPr();
2402
2403            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2404                    SystemClock.uptimeMillis());
2405
2406            if (!mOnlyCore) {
2407                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2408                mRequiredInstallerPackage = getRequiredInstallerLPr();
2409                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2410                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2411                        mIntentFilterVerifierComponent);
2412            } else {
2413                mRequiredVerifierPackage = null;
2414                mRequiredInstallerPackage = null;
2415                mIntentFilterVerifierComponent = null;
2416                mIntentFilterVerifier = null;
2417            }
2418
2419            mInstallerService = new PackageInstallerService(context, this);
2420
2421            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2422            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2423            // both the installer and resolver must be present to enable ephemeral
2424            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2425                if (DEBUG_EPHEMERAL) {
2426                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2427                            + " installer:" + ephemeralInstallerComponent);
2428                }
2429                mEphemeralResolverComponent = ephemeralResolverComponent;
2430                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2431                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2432                mEphemeralResolverConnection =
2433                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2434            } else {
2435                if (DEBUG_EPHEMERAL) {
2436                    final String missingComponent =
2437                            (ephemeralResolverComponent == null)
2438                            ? (ephemeralInstallerComponent == null)
2439                                    ? "resolver and installer"
2440                                    : "resolver"
2441                            : "installer";
2442                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2443                }
2444                mEphemeralResolverComponent = null;
2445                mEphemeralInstallerComponent = null;
2446                mEphemeralResolverConnection = null;
2447            }
2448
2449            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2450        } // synchronized (mPackages)
2451        } // synchronized (mInstallLock)
2452
2453        // Now after opening every single application zip, make sure they
2454        // are all flushed.  Not really needed, but keeps things nice and
2455        // tidy.
2456        Runtime.getRuntime().gc();
2457
2458        // The initial scanning above does many calls into installd while
2459        // holding the mPackages lock, but we're mostly interested in yelling
2460        // once we have a booted system.
2461        mInstaller.setWarnIfHeld(mPackages);
2462
2463        // Expose private service for system components to use.
2464        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2465    }
2466
2467    @Override
2468    public boolean isFirstBoot() {
2469        return !mRestoredSettings;
2470    }
2471
2472    @Override
2473    public boolean isOnlyCoreApps() {
2474        return mOnlyCore;
2475    }
2476
2477    @Override
2478    public boolean isUpgrade() {
2479        return mIsUpgrade;
2480    }
2481
2482    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2483        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2484
2485        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2486                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2487        if (matches.size() == 1) {
2488            return matches.get(0).getComponentInfo().packageName;
2489        } else {
2490            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2491            return null;
2492        }
2493    }
2494
2495    private @NonNull String getRequiredInstallerLPr() {
2496        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2497        intent.addCategory(Intent.CATEGORY_DEFAULT);
2498        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2499
2500        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2501                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2502        if (matches.size() == 1) {
2503            return matches.get(0).getComponentInfo().packageName;
2504        } else {
2505            throw new RuntimeException("There must be exactly one installer; found " + matches);
2506        }
2507    }
2508
2509    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2510        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2511
2512        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2513                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2514        ResolveInfo best = null;
2515        final int N = matches.size();
2516        for (int i = 0; i < N; i++) {
2517            final ResolveInfo cur = matches.get(i);
2518            final String packageName = cur.getComponentInfo().packageName;
2519            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2520                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2521                continue;
2522            }
2523
2524            if (best == null || cur.priority > best.priority) {
2525                best = cur;
2526            }
2527        }
2528
2529        if (best != null) {
2530            return best.getComponentInfo().getComponentName();
2531        } else {
2532            throw new RuntimeException("There must be at least one intent filter verifier");
2533        }
2534    }
2535
2536    private @Nullable ComponentName getEphemeralResolverLPr() {
2537        final String[] packageArray =
2538                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2539        if (packageArray.length == 0) {
2540            if (DEBUG_EPHEMERAL) {
2541                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2542            }
2543            return null;
2544        }
2545
2546        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2547        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2548                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2549
2550        final int N = resolvers.size();
2551        if (N == 0) {
2552            if (DEBUG_EPHEMERAL) {
2553                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2554            }
2555            return null;
2556        }
2557
2558        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2559        for (int i = 0; i < N; i++) {
2560            final ResolveInfo info = resolvers.get(i);
2561
2562            if (info.serviceInfo == null) {
2563                continue;
2564            }
2565
2566            final String packageName = info.serviceInfo.packageName;
2567            if (!possiblePackages.contains(packageName)) {
2568                if (DEBUG_EPHEMERAL) {
2569                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2570                            + " pkg: " + packageName + ", info:" + info);
2571                }
2572                continue;
2573            }
2574
2575            if (DEBUG_EPHEMERAL) {
2576                Slog.v(TAG, "Ephemeral resolver found;"
2577                        + " pkg: " + packageName + ", info:" + info);
2578            }
2579            return new ComponentName(packageName, info.serviceInfo.name);
2580        }
2581        if (DEBUG_EPHEMERAL) {
2582            Slog.v(TAG, "Ephemeral resolver NOT found");
2583        }
2584        return null;
2585    }
2586
2587    private @Nullable ComponentName getEphemeralInstallerLPr() {
2588        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2589        intent.addCategory(Intent.CATEGORY_DEFAULT);
2590        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2591
2592        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2593                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2594        if (matches.size() == 0) {
2595            return null;
2596        } else if (matches.size() == 1) {
2597            return matches.get(0).getComponentInfo().getComponentName();
2598        } else {
2599            throw new RuntimeException(
2600                    "There must be at most one ephemeral installer; found " + matches);
2601        }
2602    }
2603
2604    private void primeDomainVerificationsLPw(int userId) {
2605        if (DEBUG_DOMAIN_VERIFICATION) {
2606            Slog.d(TAG, "Priming domain verifications in user " + userId);
2607        }
2608
2609        SystemConfig systemConfig = SystemConfig.getInstance();
2610        ArraySet<String> packages = systemConfig.getLinkedApps();
2611        ArraySet<String> domains = new ArraySet<String>();
2612
2613        for (String packageName : packages) {
2614            PackageParser.Package pkg = mPackages.get(packageName);
2615            if (pkg != null) {
2616                if (!pkg.isSystemApp()) {
2617                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2618                    continue;
2619                }
2620
2621                domains.clear();
2622                for (PackageParser.Activity a : pkg.activities) {
2623                    for (ActivityIntentInfo filter : a.intents) {
2624                        if (hasValidDomains(filter)) {
2625                            domains.addAll(filter.getHostsList());
2626                        }
2627                    }
2628                }
2629
2630                if (domains.size() > 0) {
2631                    if (DEBUG_DOMAIN_VERIFICATION) {
2632                        Slog.v(TAG, "      + " + packageName);
2633                    }
2634                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2635                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2636                    // and then 'always' in the per-user state actually used for intent resolution.
2637                    final IntentFilterVerificationInfo ivi;
2638                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2639                            new ArrayList<String>(domains));
2640                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2641                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2642                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2643                } else {
2644                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2645                            + "' does not handle web links");
2646                }
2647            } else {
2648                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2649            }
2650        }
2651
2652        scheduleWritePackageRestrictionsLocked(userId);
2653        scheduleWriteSettingsLocked();
2654    }
2655
2656    private void applyFactoryDefaultBrowserLPw(int userId) {
2657        // The default browser app's package name is stored in a string resource,
2658        // with a product-specific overlay used for vendor customization.
2659        String browserPkg = mContext.getResources().getString(
2660                com.android.internal.R.string.default_browser);
2661        if (!TextUtils.isEmpty(browserPkg)) {
2662            // non-empty string => required to be a known package
2663            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2664            if (ps == null) {
2665                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2666                browserPkg = null;
2667            } else {
2668                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2669            }
2670        }
2671
2672        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2673        // default.  If there's more than one, just leave everything alone.
2674        if (browserPkg == null) {
2675            calculateDefaultBrowserLPw(userId);
2676        }
2677    }
2678
2679    private void calculateDefaultBrowserLPw(int userId) {
2680        List<String> allBrowsers = resolveAllBrowserApps(userId);
2681        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2682        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2683    }
2684
2685    private List<String> resolveAllBrowserApps(int userId) {
2686        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2687        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2688                PackageManager.MATCH_ALL, userId);
2689
2690        final int count = list.size();
2691        List<String> result = new ArrayList<String>(count);
2692        for (int i=0; i<count; i++) {
2693            ResolveInfo info = list.get(i);
2694            if (info.activityInfo == null
2695                    || !info.handleAllWebDataURI
2696                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2697                    || result.contains(info.activityInfo.packageName)) {
2698                continue;
2699            }
2700            result.add(info.activityInfo.packageName);
2701        }
2702
2703        return result;
2704    }
2705
2706    private boolean packageIsBrowser(String packageName, int userId) {
2707        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2708                PackageManager.MATCH_ALL, userId);
2709        final int N = list.size();
2710        for (int i = 0; i < N; i++) {
2711            ResolveInfo info = list.get(i);
2712            if (packageName.equals(info.activityInfo.packageName)) {
2713                return true;
2714            }
2715        }
2716        return false;
2717    }
2718
2719    private void checkDefaultBrowser() {
2720        final int myUserId = UserHandle.myUserId();
2721        final String packageName = getDefaultBrowserPackageName(myUserId);
2722        if (packageName != null) {
2723            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2724            if (info == null) {
2725                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2726                synchronized (mPackages) {
2727                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2728                }
2729            }
2730        }
2731    }
2732
2733    @Override
2734    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2735            throws RemoteException {
2736        try {
2737            return super.onTransact(code, data, reply, flags);
2738        } catch (RuntimeException e) {
2739            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2740                Slog.wtf(TAG, "Package Manager Crash", e);
2741            }
2742            throw e;
2743        }
2744    }
2745
2746    void cleanupInstallFailedPackage(PackageSetting ps) {
2747        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2748
2749        removeDataDirsLI(ps.volumeUuid, ps.name);
2750        if (ps.codePath != null) {
2751            removeCodePathLI(ps.codePath);
2752        }
2753        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2754            if (ps.resourcePath.isDirectory()) {
2755                FileUtils.deleteContents(ps.resourcePath);
2756            }
2757            ps.resourcePath.delete();
2758        }
2759        mSettings.removePackageLPw(ps.name);
2760    }
2761
2762    static int[] appendInts(int[] cur, int[] add) {
2763        if (add == null) return cur;
2764        if (cur == null) return add;
2765        final int N = add.length;
2766        for (int i=0; i<N; i++) {
2767            cur = appendInt(cur, add[i]);
2768        }
2769        return cur;
2770    }
2771
2772    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2773        if (!sUserManager.exists(userId)) return null;
2774        final PackageSetting ps = (PackageSetting) p.mExtras;
2775        if (ps == null) {
2776            return null;
2777        }
2778
2779        final PermissionsState permissionsState = ps.getPermissionsState();
2780
2781        final int[] gids = permissionsState.computeGids(userId);
2782        final Set<String> permissions = permissionsState.getPermissions(userId);
2783        final PackageUserState state = ps.readUserState(userId);
2784
2785        return PackageParser.generatePackageInfo(p, gids, flags,
2786                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2787    }
2788
2789    @Override
2790    public void checkPackageStartable(String packageName, int userId) {
2791        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2792
2793        synchronized (mPackages) {
2794            final PackageSetting ps = mSettings.mPackages.get(packageName);
2795            if (ps == null) {
2796                throw new SecurityException("Package " + packageName + " was not found!");
2797            }
2798
2799            if (ps.frozen) {
2800                throw new SecurityException("Package " + packageName + " is currently frozen!");
2801            }
2802
2803            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2804                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2805                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2806            }
2807        }
2808    }
2809
2810    @Override
2811    public boolean isPackageAvailable(String packageName, int userId) {
2812        if (!sUserManager.exists(userId)) return false;
2813        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2814        synchronized (mPackages) {
2815            PackageParser.Package p = mPackages.get(packageName);
2816            if (p != null) {
2817                final PackageSetting ps = (PackageSetting) p.mExtras;
2818                if (ps != null) {
2819                    final PackageUserState state = ps.readUserState(userId);
2820                    if (state != null) {
2821                        return PackageParser.isAvailable(state);
2822                    }
2823                }
2824            }
2825        }
2826        return false;
2827    }
2828
2829    @Override
2830    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2831        if (!sUserManager.exists(userId)) return null;
2832        flags = updateFlagsForPackage(flags, userId, packageName);
2833        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2834        // reader
2835        synchronized (mPackages) {
2836            PackageParser.Package p = mPackages.get(packageName);
2837            if (DEBUG_PACKAGE_INFO)
2838                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2839            if (p != null) {
2840                return generatePackageInfo(p, flags, userId);
2841            }
2842            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2843                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2844            }
2845        }
2846        return null;
2847    }
2848
2849    @Override
2850    public String[] currentToCanonicalPackageNames(String[] names) {
2851        String[] out = new String[names.length];
2852        // reader
2853        synchronized (mPackages) {
2854            for (int i=names.length-1; i>=0; i--) {
2855                PackageSetting ps = mSettings.mPackages.get(names[i]);
2856                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2857            }
2858        }
2859        return out;
2860    }
2861
2862    @Override
2863    public String[] canonicalToCurrentPackageNames(String[] names) {
2864        String[] out = new String[names.length];
2865        // reader
2866        synchronized (mPackages) {
2867            for (int i=names.length-1; i>=0; i--) {
2868                String cur = mSettings.mRenamedPackages.get(names[i]);
2869                out[i] = cur != null ? cur : names[i];
2870            }
2871        }
2872        return out;
2873    }
2874
2875    @Override
2876    public int getPackageUid(String packageName, int flags, int userId) {
2877        if (!sUserManager.exists(userId)) return -1;
2878        flags = updateFlagsForPackage(flags, userId, packageName);
2879        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2880
2881        // reader
2882        synchronized (mPackages) {
2883            final PackageParser.Package p = mPackages.get(packageName);
2884            if (p != null && p.isMatch(flags)) {
2885                return UserHandle.getUid(userId, p.applicationInfo.uid);
2886            }
2887            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2888                final PackageSetting ps = mSettings.mPackages.get(packageName);
2889                if (ps != null && ps.isMatch(flags)) {
2890                    return UserHandle.getUid(userId, ps.appId);
2891                }
2892            }
2893        }
2894
2895        return -1;
2896    }
2897
2898    @Override
2899    public int[] getPackageGids(String packageName, int flags, int userId) {
2900        if (!sUserManager.exists(userId)) return null;
2901        flags = updateFlagsForPackage(flags, userId, packageName);
2902        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2903                "getPackageGids");
2904
2905        // reader
2906        synchronized (mPackages) {
2907            final PackageParser.Package p = mPackages.get(packageName);
2908            if (p != null && p.isMatch(flags)) {
2909                PackageSetting ps = (PackageSetting) p.mExtras;
2910                return ps.getPermissionsState().computeGids(userId);
2911            }
2912            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2913                final PackageSetting ps = mSettings.mPackages.get(packageName);
2914                if (ps != null && ps.isMatch(flags)) {
2915                    return ps.getPermissionsState().computeGids(userId);
2916                }
2917            }
2918        }
2919
2920        return null;
2921    }
2922
2923    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2924        if (bp.perm != null) {
2925            return PackageParser.generatePermissionInfo(bp.perm, flags);
2926        }
2927        PermissionInfo pi = new PermissionInfo();
2928        pi.name = bp.name;
2929        pi.packageName = bp.sourcePackage;
2930        pi.nonLocalizedLabel = bp.name;
2931        pi.protectionLevel = bp.protectionLevel;
2932        return pi;
2933    }
2934
2935    @Override
2936    public PermissionInfo getPermissionInfo(String name, int flags) {
2937        // reader
2938        synchronized (mPackages) {
2939            final BasePermission p = mSettings.mPermissions.get(name);
2940            if (p != null) {
2941                return generatePermissionInfo(p, flags);
2942            }
2943            return null;
2944        }
2945    }
2946
2947    @Override
2948    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2949        // reader
2950        synchronized (mPackages) {
2951            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2952            for (BasePermission p : mSettings.mPermissions.values()) {
2953                if (group == null) {
2954                    if (p.perm == null || p.perm.info.group == null) {
2955                        out.add(generatePermissionInfo(p, flags));
2956                    }
2957                } else {
2958                    if (p.perm != null && group.equals(p.perm.info.group)) {
2959                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2960                    }
2961                }
2962            }
2963
2964            if (out.size() > 0) {
2965                return out;
2966            }
2967            return mPermissionGroups.containsKey(group) ? out : null;
2968        }
2969    }
2970
2971    @Override
2972    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2973        // reader
2974        synchronized (mPackages) {
2975            return PackageParser.generatePermissionGroupInfo(
2976                    mPermissionGroups.get(name), flags);
2977        }
2978    }
2979
2980    @Override
2981    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2982        // reader
2983        synchronized (mPackages) {
2984            final int N = mPermissionGroups.size();
2985            ArrayList<PermissionGroupInfo> out
2986                    = new ArrayList<PermissionGroupInfo>(N);
2987            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2988                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2989            }
2990            return out;
2991        }
2992    }
2993
2994    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2995            int userId) {
2996        if (!sUserManager.exists(userId)) return null;
2997        PackageSetting ps = mSettings.mPackages.get(packageName);
2998        if (ps != null) {
2999            if (ps.pkg == null) {
3000                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3001                        flags, userId);
3002                if (pInfo != null) {
3003                    return pInfo.applicationInfo;
3004                }
3005                return null;
3006            }
3007            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3008                    ps.readUserState(userId), userId);
3009        }
3010        return null;
3011    }
3012
3013    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3014            int userId) {
3015        if (!sUserManager.exists(userId)) return null;
3016        PackageSetting ps = mSettings.mPackages.get(packageName);
3017        if (ps != null) {
3018            PackageParser.Package pkg = ps.pkg;
3019            if (pkg == null) {
3020                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3021                    return null;
3022                }
3023                // Only data remains, so we aren't worried about code paths
3024                pkg = new PackageParser.Package(packageName);
3025                pkg.applicationInfo.packageName = packageName;
3026                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3027                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3028                pkg.applicationInfo.uid = ps.appId;
3029                pkg.applicationInfo.initForUser(userId);
3030                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3031                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3032            }
3033            return generatePackageInfo(pkg, flags, userId);
3034        }
3035        return null;
3036    }
3037
3038    @Override
3039    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3040        if (!sUserManager.exists(userId)) return null;
3041        flags = updateFlagsForApplication(flags, userId, packageName);
3042        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3043        // writer
3044        synchronized (mPackages) {
3045            PackageParser.Package p = mPackages.get(packageName);
3046            if (DEBUG_PACKAGE_INFO) Log.v(
3047                    TAG, "getApplicationInfo " + packageName
3048                    + ": " + p);
3049            if (p != null) {
3050                PackageSetting ps = mSettings.mPackages.get(packageName);
3051                if (ps == null) return null;
3052                // Note: isEnabledLP() does not apply here - always return info
3053                return PackageParser.generateApplicationInfo(
3054                        p, flags, ps.readUserState(userId), userId);
3055            }
3056            if ("android".equals(packageName)||"system".equals(packageName)) {
3057                return mAndroidApplication;
3058            }
3059            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3060                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3061            }
3062        }
3063        return null;
3064    }
3065
3066    @Override
3067    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3068            final IPackageDataObserver observer) {
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 (observer != null) {
3085                    try {
3086                        observer.onRemoveCompleted(null, success);
3087                    } catch (RemoteException e) {
3088                        Slog.w(TAG, "RemoveException when invoking call back");
3089                    }
3090                }
3091            }
3092        });
3093    }
3094
3095    @Override
3096    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3097            final IntentSender pi) {
3098        mContext.enforceCallingOrSelfPermission(
3099                android.Manifest.permission.CLEAR_APP_CACHE, null);
3100        // Queue up an async operation since clearing cache may take a little while.
3101        mHandler.post(new Runnable() {
3102            public void run() {
3103                mHandler.removeCallbacks(this);
3104                boolean success = true;
3105                synchronized (mInstallLock) {
3106                    try {
3107                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3108                    } catch (InstallerException e) {
3109                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3110                        success = false;
3111                    }
3112                }
3113                if(pi != null) {
3114                    try {
3115                        // Callback via pending intent
3116                        int code = success ? 1 : 0;
3117                        pi.sendIntent(null, code, null,
3118                                null, null);
3119                    } catch (SendIntentException e1) {
3120                        Slog.i(TAG, "Failed to send pending intent");
3121                    }
3122                }
3123            }
3124        });
3125    }
3126
3127    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3128        synchronized (mInstallLock) {
3129            try {
3130                mInstaller.freeCache(volumeUuid, freeStorageSize);
3131            } catch (InstallerException e) {
3132                throw new IOException("Failed to free enough space", e);
3133            }
3134        }
3135    }
3136
3137    /**
3138     * Return if the user key is currently unlocked.
3139     */
3140    private boolean isUserKeyUnlocked(int userId) {
3141        if (StorageManager.isFileBasedEncryptionEnabled()) {
3142            final IMountService mount = IMountService.Stub
3143                    .asInterface(ServiceManager.getService("mount"));
3144            if (mount == null) {
3145                Slog.w(TAG, "Early during boot, assuming locked");
3146                return false;
3147            }
3148            final long token = Binder.clearCallingIdentity();
3149            try {
3150                return mount.isUserKeyUnlocked(userId);
3151            } catch (RemoteException e) {
3152                throw e.rethrowAsRuntimeException();
3153            } finally {
3154                Binder.restoreCallingIdentity(token);
3155            }
3156        } else {
3157            return true;
3158        }
3159    }
3160
3161    /**
3162     * Update given flags based on encryption status of current user.
3163     */
3164    private int updateFlags(int flags, int userId) {
3165        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3166                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3167            // Caller expressed an explicit opinion about what encryption
3168            // aware/unaware components they want to see, so fall through and
3169            // give them what they want
3170        } else {
3171            // Caller expressed no opinion, so match based on user state
3172            if (isUserKeyUnlocked(userId)) {
3173                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3174            } else {
3175                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3176            }
3177        }
3178
3179        // Safe mode means we should ignore any third-party apps
3180        if (mSafeMode) {
3181            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3182        }
3183
3184        return flags;
3185    }
3186
3187    /**
3188     * Update given flags when being used to request {@link PackageInfo}.
3189     */
3190    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3191        boolean triaged = true;
3192        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3193                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3194            // Caller is asking for component details, so they'd better be
3195            // asking for specific encryption matching behavior, or be triaged
3196            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3197                    | PackageManager.MATCH_ENCRYPTION_AWARE
3198                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3199                triaged = false;
3200            }
3201        }
3202        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3203                | PackageManager.MATCH_SYSTEM_ONLY
3204                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3205            triaged = false;
3206        }
3207        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3208            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3209                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3210        }
3211        return updateFlags(flags, userId);
3212    }
3213
3214    /**
3215     * Update given flags when being used to request {@link ApplicationInfo}.
3216     */
3217    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3218        return updateFlagsForPackage(flags, userId, cookie);
3219    }
3220
3221    /**
3222     * Update given flags when being used to request {@link ComponentInfo}.
3223     */
3224    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3225        if (cookie instanceof Intent) {
3226            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3227                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3228            }
3229        }
3230
3231        boolean triaged = true;
3232        // Caller is asking for component details, so they'd better be
3233        // asking for specific encryption matching behavior, or be triaged
3234        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3235                | PackageManager.MATCH_ENCRYPTION_AWARE
3236                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3237            triaged = false;
3238        }
3239        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3240            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3241                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3242        }
3243        return updateFlags(flags, userId);
3244    }
3245
3246    /**
3247     * Update given flags when being used to request {@link ResolveInfo}.
3248     */
3249    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3250        return updateFlagsForComponent(flags, userId, cookie);
3251    }
3252
3253    @Override
3254    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3255        if (!sUserManager.exists(userId)) return null;
3256        flags = updateFlagsForComponent(flags, userId, component);
3257        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3258        synchronized (mPackages) {
3259            PackageParser.Activity a = mActivities.mActivities.get(component);
3260
3261            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3262            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3263                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3264                if (ps == null) return null;
3265                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3266                        userId);
3267            }
3268            if (mResolveComponentName.equals(component)) {
3269                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3270                        new PackageUserState(), userId);
3271            }
3272        }
3273        return null;
3274    }
3275
3276    @Override
3277    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3278            String resolvedType) {
3279        synchronized (mPackages) {
3280            if (component.equals(mResolveComponentName)) {
3281                // The resolver supports EVERYTHING!
3282                return true;
3283            }
3284            PackageParser.Activity a = mActivities.mActivities.get(component);
3285            if (a == null) {
3286                return false;
3287            }
3288            for (int i=0; i<a.intents.size(); i++) {
3289                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3290                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3291                    return true;
3292                }
3293            }
3294            return false;
3295        }
3296    }
3297
3298    @Override
3299    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3300        if (!sUserManager.exists(userId)) return null;
3301        flags = updateFlagsForComponent(flags, userId, component);
3302        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3303        synchronized (mPackages) {
3304            PackageParser.Activity a = mReceivers.mActivities.get(component);
3305            if (DEBUG_PACKAGE_INFO) Log.v(
3306                TAG, "getReceiverInfo " + component + ": " + a);
3307            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3308                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3309                if (ps == null) return null;
3310                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3311                        userId);
3312            }
3313        }
3314        return null;
3315    }
3316
3317    @Override
3318    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3319        if (!sUserManager.exists(userId)) return null;
3320        flags = updateFlagsForComponent(flags, userId, component);
3321        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3322        synchronized (mPackages) {
3323            PackageParser.Service s = mServices.mServices.get(component);
3324            if (DEBUG_PACKAGE_INFO) Log.v(
3325                TAG, "getServiceInfo " + component + ": " + s);
3326            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3327                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3328                if (ps == null) return null;
3329                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3330                        userId);
3331            }
3332        }
3333        return null;
3334    }
3335
3336    @Override
3337    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3338        if (!sUserManager.exists(userId)) return null;
3339        flags = updateFlagsForComponent(flags, userId, component);
3340        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3341        synchronized (mPackages) {
3342            PackageParser.Provider p = mProviders.mProviders.get(component);
3343            if (DEBUG_PACKAGE_INFO) Log.v(
3344                TAG, "getProviderInfo " + component + ": " + p);
3345            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3346                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3347                if (ps == null) return null;
3348                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3349                        userId);
3350            }
3351        }
3352        return null;
3353    }
3354
3355    @Override
3356    public String[] getSystemSharedLibraryNames() {
3357        Set<String> libSet;
3358        synchronized (mPackages) {
3359            libSet = mSharedLibraries.keySet();
3360            int size = libSet.size();
3361            if (size > 0) {
3362                String[] libs = new String[size];
3363                libSet.toArray(libs);
3364                return libs;
3365            }
3366        }
3367        return null;
3368    }
3369
3370    /**
3371     * @hide
3372     */
3373    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3374        synchronized (mPackages) {
3375            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3376            if (lib != null && lib.apk != null) {
3377                return mPackages.get(lib.apk);
3378            }
3379        }
3380        return null;
3381    }
3382
3383    @Override
3384    public FeatureInfo[] getSystemAvailableFeatures() {
3385        Collection<FeatureInfo> featSet;
3386        synchronized (mPackages) {
3387            featSet = mAvailableFeatures.values();
3388            int size = featSet.size();
3389            if (size > 0) {
3390                FeatureInfo[] features = new FeatureInfo[size+1];
3391                featSet.toArray(features);
3392                FeatureInfo fi = new FeatureInfo();
3393                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3394                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3395                features[size] = fi;
3396                return features;
3397            }
3398        }
3399        return null;
3400    }
3401
3402    @Override
3403    public boolean hasSystemFeature(String name) {
3404        synchronized (mPackages) {
3405            return mAvailableFeatures.containsKey(name);
3406        }
3407    }
3408
3409    @Override
3410    public int checkPermission(String permName, String pkgName, int userId) {
3411        if (!sUserManager.exists(userId)) {
3412            return PackageManager.PERMISSION_DENIED;
3413        }
3414
3415        synchronized (mPackages) {
3416            final PackageParser.Package p = mPackages.get(pkgName);
3417            if (p != null && p.mExtras != null) {
3418                final PackageSetting ps = (PackageSetting) p.mExtras;
3419                final PermissionsState permissionsState = ps.getPermissionsState();
3420                if (permissionsState.hasPermission(permName, userId)) {
3421                    return PackageManager.PERMISSION_GRANTED;
3422                }
3423                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3424                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3425                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3426                    return PackageManager.PERMISSION_GRANTED;
3427                }
3428            }
3429        }
3430
3431        return PackageManager.PERMISSION_DENIED;
3432    }
3433
3434    @Override
3435    public int checkUidPermission(String permName, int uid) {
3436        final int userId = UserHandle.getUserId(uid);
3437
3438        if (!sUserManager.exists(userId)) {
3439            return PackageManager.PERMISSION_DENIED;
3440        }
3441
3442        synchronized (mPackages) {
3443            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3444            if (obj != null) {
3445                final SettingBase ps = (SettingBase) obj;
3446                final PermissionsState permissionsState = ps.getPermissionsState();
3447                if (permissionsState.hasPermission(permName, userId)) {
3448                    return PackageManager.PERMISSION_GRANTED;
3449                }
3450                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3451                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3452                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3453                    return PackageManager.PERMISSION_GRANTED;
3454                }
3455            } else {
3456                ArraySet<String> perms = mSystemPermissions.get(uid);
3457                if (perms != null) {
3458                    if (perms.contains(permName)) {
3459                        return PackageManager.PERMISSION_GRANTED;
3460                    }
3461                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3462                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3463                        return PackageManager.PERMISSION_GRANTED;
3464                    }
3465                }
3466            }
3467        }
3468
3469        return PackageManager.PERMISSION_DENIED;
3470    }
3471
3472    @Override
3473    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3474        if (UserHandle.getCallingUserId() != userId) {
3475            mContext.enforceCallingPermission(
3476                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3477                    "isPermissionRevokedByPolicy for user " + userId);
3478        }
3479
3480        if (checkPermission(permission, packageName, userId)
3481                == PackageManager.PERMISSION_GRANTED) {
3482            return false;
3483        }
3484
3485        final long identity = Binder.clearCallingIdentity();
3486        try {
3487            final int flags = getPermissionFlags(permission, packageName, userId);
3488            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3489        } finally {
3490            Binder.restoreCallingIdentity(identity);
3491        }
3492    }
3493
3494    @Override
3495    public String getPermissionControllerPackageName() {
3496        synchronized (mPackages) {
3497            return mRequiredInstallerPackage;
3498        }
3499    }
3500
3501    /**
3502     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3503     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3504     * @param checkShell TODO(yamasani):
3505     * @param message the message to log on security exception
3506     */
3507    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3508            boolean checkShell, String message) {
3509        if (userId < 0) {
3510            throw new IllegalArgumentException("Invalid userId " + userId);
3511        }
3512        if (checkShell) {
3513            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3514        }
3515        if (userId == UserHandle.getUserId(callingUid)) return;
3516        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3517            if (requireFullPermission) {
3518                mContext.enforceCallingOrSelfPermission(
3519                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3520            } else {
3521                try {
3522                    mContext.enforceCallingOrSelfPermission(
3523                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3524                } catch (SecurityException se) {
3525                    mContext.enforceCallingOrSelfPermission(
3526                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3527                }
3528            }
3529        }
3530    }
3531
3532    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3533        if (callingUid == Process.SHELL_UID) {
3534            if (userHandle >= 0
3535                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3536                throw new SecurityException("Shell does not have permission to access user "
3537                        + userHandle);
3538            } else if (userHandle < 0) {
3539                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3540                        + Debug.getCallers(3));
3541            }
3542        }
3543    }
3544
3545    private BasePermission findPermissionTreeLP(String permName) {
3546        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3547            if (permName.startsWith(bp.name) &&
3548                    permName.length() > bp.name.length() &&
3549                    permName.charAt(bp.name.length()) == '.') {
3550                return bp;
3551            }
3552        }
3553        return null;
3554    }
3555
3556    private BasePermission checkPermissionTreeLP(String permName) {
3557        if (permName != null) {
3558            BasePermission bp = findPermissionTreeLP(permName);
3559            if (bp != null) {
3560                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3561                    return bp;
3562                }
3563                throw new SecurityException("Calling uid "
3564                        + Binder.getCallingUid()
3565                        + " is not allowed to add to permission tree "
3566                        + bp.name + " owned by uid " + bp.uid);
3567            }
3568        }
3569        throw new SecurityException("No permission tree found for " + permName);
3570    }
3571
3572    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3573        if (s1 == null) {
3574            return s2 == null;
3575        }
3576        if (s2 == null) {
3577            return false;
3578        }
3579        if (s1.getClass() != s2.getClass()) {
3580            return false;
3581        }
3582        return s1.equals(s2);
3583    }
3584
3585    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3586        if (pi1.icon != pi2.icon) return false;
3587        if (pi1.logo != pi2.logo) return false;
3588        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3589        if (!compareStrings(pi1.name, pi2.name)) return false;
3590        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3591        // We'll take care of setting this one.
3592        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3593        // These are not currently stored in settings.
3594        //if (!compareStrings(pi1.group, pi2.group)) return false;
3595        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3596        //if (pi1.labelRes != pi2.labelRes) return false;
3597        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3598        return true;
3599    }
3600
3601    int permissionInfoFootprint(PermissionInfo info) {
3602        int size = info.name.length();
3603        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3604        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3605        return size;
3606    }
3607
3608    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3609        int size = 0;
3610        for (BasePermission perm : mSettings.mPermissions.values()) {
3611            if (perm.uid == tree.uid) {
3612                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3613            }
3614        }
3615        return size;
3616    }
3617
3618    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3619        // We calculate the max size of permissions defined by this uid and throw
3620        // if that plus the size of 'info' would exceed our stated maximum.
3621        if (tree.uid != Process.SYSTEM_UID) {
3622            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3623            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3624                throw new SecurityException("Permission tree size cap exceeded");
3625            }
3626        }
3627    }
3628
3629    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3630        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3631            throw new SecurityException("Label must be specified in permission");
3632        }
3633        BasePermission tree = checkPermissionTreeLP(info.name);
3634        BasePermission bp = mSettings.mPermissions.get(info.name);
3635        boolean added = bp == null;
3636        boolean changed = true;
3637        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3638        if (added) {
3639            enforcePermissionCapLocked(info, tree);
3640            bp = new BasePermission(info.name, tree.sourcePackage,
3641                    BasePermission.TYPE_DYNAMIC);
3642        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3643            throw new SecurityException(
3644                    "Not allowed to modify non-dynamic permission "
3645                    + info.name);
3646        } else {
3647            if (bp.protectionLevel == fixedLevel
3648                    && bp.perm.owner.equals(tree.perm.owner)
3649                    && bp.uid == tree.uid
3650                    && comparePermissionInfos(bp.perm.info, info)) {
3651                changed = false;
3652            }
3653        }
3654        bp.protectionLevel = fixedLevel;
3655        info = new PermissionInfo(info);
3656        info.protectionLevel = fixedLevel;
3657        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3658        bp.perm.info.packageName = tree.perm.info.packageName;
3659        bp.uid = tree.uid;
3660        if (added) {
3661            mSettings.mPermissions.put(info.name, bp);
3662        }
3663        if (changed) {
3664            if (!async) {
3665                mSettings.writeLPr();
3666            } else {
3667                scheduleWriteSettingsLocked();
3668            }
3669        }
3670        return added;
3671    }
3672
3673    @Override
3674    public boolean addPermission(PermissionInfo info) {
3675        synchronized (mPackages) {
3676            return addPermissionLocked(info, false);
3677        }
3678    }
3679
3680    @Override
3681    public boolean addPermissionAsync(PermissionInfo info) {
3682        synchronized (mPackages) {
3683            return addPermissionLocked(info, true);
3684        }
3685    }
3686
3687    @Override
3688    public void removePermission(String name) {
3689        synchronized (mPackages) {
3690            checkPermissionTreeLP(name);
3691            BasePermission bp = mSettings.mPermissions.get(name);
3692            if (bp != null) {
3693                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3694                    throw new SecurityException(
3695                            "Not allowed to modify non-dynamic permission "
3696                            + name);
3697                }
3698                mSettings.mPermissions.remove(name);
3699                mSettings.writeLPr();
3700            }
3701        }
3702    }
3703
3704    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3705            BasePermission bp) {
3706        int index = pkg.requestedPermissions.indexOf(bp.name);
3707        if (index == -1) {
3708            throw new SecurityException("Package " + pkg.packageName
3709                    + " has not requested permission " + bp.name);
3710        }
3711        if (!bp.isRuntime() && !bp.isDevelopment()) {
3712            throw new SecurityException("Permission " + bp.name
3713                    + " is not a changeable permission type");
3714        }
3715    }
3716
3717    @Override
3718    public void grantRuntimePermission(String packageName, String name, final int userId) {
3719        if (!sUserManager.exists(userId)) {
3720            Log.e(TAG, "No such user:" + userId);
3721            return;
3722        }
3723
3724        mContext.enforceCallingOrSelfPermission(
3725                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3726                "grantRuntimePermission");
3727
3728        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3729                "grantRuntimePermission");
3730
3731        final int uid;
3732        final SettingBase sb;
3733
3734        synchronized (mPackages) {
3735            final PackageParser.Package pkg = mPackages.get(packageName);
3736            if (pkg == null) {
3737                throw new IllegalArgumentException("Unknown package: " + packageName);
3738            }
3739
3740            final BasePermission bp = mSettings.mPermissions.get(name);
3741            if (bp == null) {
3742                throw new IllegalArgumentException("Unknown permission: " + name);
3743            }
3744
3745            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3746
3747            // If a permission review is required for legacy apps we represent
3748            // their permissions as always granted runtime ones since we need
3749            // to keep the review required permission flag per user while an
3750            // install permission's state is shared across all users.
3751            if (Build.PERMISSIONS_REVIEW_REQUIRED
3752                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3753                    && bp.isRuntime()) {
3754                return;
3755            }
3756
3757            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3758            sb = (SettingBase) pkg.mExtras;
3759            if (sb == null) {
3760                throw new IllegalArgumentException("Unknown package: " + packageName);
3761            }
3762
3763            final PermissionsState permissionsState = sb.getPermissionsState();
3764
3765            final int flags = permissionsState.getPermissionFlags(name, userId);
3766            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3767                throw new SecurityException("Cannot grant system fixed permission "
3768                        + name + " for package " + packageName);
3769            }
3770
3771            if (bp.isDevelopment()) {
3772                // Development permissions must be handled specially, since they are not
3773                // normal runtime permissions.  For now they apply to all users.
3774                if (permissionsState.grantInstallPermission(bp) !=
3775                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3776                    scheduleWriteSettingsLocked();
3777                }
3778                return;
3779            }
3780
3781            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3782                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3783                return;
3784            }
3785
3786            final int result = permissionsState.grantRuntimePermission(bp, userId);
3787            switch (result) {
3788                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3789                    return;
3790                }
3791
3792                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3793                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3794                    mHandler.post(new Runnable() {
3795                        @Override
3796                        public void run() {
3797                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3798                        }
3799                    });
3800                }
3801                break;
3802            }
3803
3804            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3805
3806            // Not critical if that is lost - app has to request again.
3807            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3808        }
3809
3810        // Only need to do this if user is initialized. Otherwise it's a new user
3811        // and there are no processes running as the user yet and there's no need
3812        // to make an expensive call to remount processes for the changed permissions.
3813        if (READ_EXTERNAL_STORAGE.equals(name)
3814                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3815            final long token = Binder.clearCallingIdentity();
3816            try {
3817                if (sUserManager.isInitialized(userId)) {
3818                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3819                            MountServiceInternal.class);
3820                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3821                }
3822            } finally {
3823                Binder.restoreCallingIdentity(token);
3824            }
3825        }
3826    }
3827
3828    @Override
3829    public void revokeRuntimePermission(String packageName, String name, int userId) {
3830        if (!sUserManager.exists(userId)) {
3831            Log.e(TAG, "No such user:" + userId);
3832            return;
3833        }
3834
3835        mContext.enforceCallingOrSelfPermission(
3836                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3837                "revokeRuntimePermission");
3838
3839        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3840                "revokeRuntimePermission");
3841
3842        final int appId;
3843
3844        synchronized (mPackages) {
3845            final PackageParser.Package pkg = mPackages.get(packageName);
3846            if (pkg == null) {
3847                throw new IllegalArgumentException("Unknown package: " + packageName);
3848            }
3849
3850            final BasePermission bp = mSettings.mPermissions.get(name);
3851            if (bp == null) {
3852                throw new IllegalArgumentException("Unknown permission: " + name);
3853            }
3854
3855            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3856
3857            // If a permission review is required for legacy apps we represent
3858            // their permissions as always granted runtime ones since we need
3859            // to keep the review required permission flag per user while an
3860            // install permission's state is shared across all users.
3861            if (Build.PERMISSIONS_REVIEW_REQUIRED
3862                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3863                    && bp.isRuntime()) {
3864                return;
3865            }
3866
3867            SettingBase sb = (SettingBase) pkg.mExtras;
3868            if (sb == null) {
3869                throw new IllegalArgumentException("Unknown package: " + packageName);
3870            }
3871
3872            final PermissionsState permissionsState = sb.getPermissionsState();
3873
3874            final int flags = permissionsState.getPermissionFlags(name, userId);
3875            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3876                throw new SecurityException("Cannot revoke system fixed permission "
3877                        + name + " for package " + packageName);
3878            }
3879
3880            if (bp.isDevelopment()) {
3881                // Development permissions must be handled specially, since they are not
3882                // normal runtime permissions.  For now they apply to all users.
3883                if (permissionsState.revokeInstallPermission(bp) !=
3884                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3885                    scheduleWriteSettingsLocked();
3886                }
3887                return;
3888            }
3889
3890            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3891                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3892                return;
3893            }
3894
3895            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3896
3897            // Critical, after this call app should never have the permission.
3898            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3899
3900            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3901        }
3902
3903        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3904    }
3905
3906    @Override
3907    public void resetRuntimePermissions() {
3908        mContext.enforceCallingOrSelfPermission(
3909                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3910                "revokeRuntimePermission");
3911
3912        int callingUid = Binder.getCallingUid();
3913        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3914            mContext.enforceCallingOrSelfPermission(
3915                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3916                    "resetRuntimePermissions");
3917        }
3918
3919        synchronized (mPackages) {
3920            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3921            for (int userId : UserManagerService.getInstance().getUserIds()) {
3922                final int packageCount = mPackages.size();
3923                for (int i = 0; i < packageCount; i++) {
3924                    PackageParser.Package pkg = mPackages.valueAt(i);
3925                    if (!(pkg.mExtras instanceof PackageSetting)) {
3926                        continue;
3927                    }
3928                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3929                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3930                }
3931            }
3932        }
3933    }
3934
3935    @Override
3936    public int getPermissionFlags(String name, String packageName, int userId) {
3937        if (!sUserManager.exists(userId)) {
3938            return 0;
3939        }
3940
3941        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3942
3943        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3944                "getPermissionFlags");
3945
3946        synchronized (mPackages) {
3947            final PackageParser.Package pkg = mPackages.get(packageName);
3948            if (pkg == null) {
3949                throw new IllegalArgumentException("Unknown package: " + packageName);
3950            }
3951
3952            final BasePermission bp = mSettings.mPermissions.get(name);
3953            if (bp == null) {
3954                throw new IllegalArgumentException("Unknown permission: " + name);
3955            }
3956
3957            SettingBase sb = (SettingBase) pkg.mExtras;
3958            if (sb == null) {
3959                throw new IllegalArgumentException("Unknown package: " + packageName);
3960            }
3961
3962            PermissionsState permissionsState = sb.getPermissionsState();
3963            return permissionsState.getPermissionFlags(name, userId);
3964        }
3965    }
3966
3967    @Override
3968    public void updatePermissionFlags(String name, String packageName, int flagMask,
3969            int flagValues, int userId) {
3970        if (!sUserManager.exists(userId)) {
3971            return;
3972        }
3973
3974        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3975
3976        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3977                "updatePermissionFlags");
3978
3979        // Only the system can change these flags and nothing else.
3980        if (getCallingUid() != Process.SYSTEM_UID) {
3981            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3982            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3983            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3984            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3985            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3986        }
3987
3988        synchronized (mPackages) {
3989            final PackageParser.Package pkg = mPackages.get(packageName);
3990            if (pkg == null) {
3991                throw new IllegalArgumentException("Unknown package: " + packageName);
3992            }
3993
3994            final BasePermission bp = mSettings.mPermissions.get(name);
3995            if (bp == null) {
3996                throw new IllegalArgumentException("Unknown permission: " + name);
3997            }
3998
3999            SettingBase sb = (SettingBase) pkg.mExtras;
4000            if (sb == null) {
4001                throw new IllegalArgumentException("Unknown package: " + packageName);
4002            }
4003
4004            PermissionsState permissionsState = sb.getPermissionsState();
4005
4006            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4007
4008            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4009                // Install and runtime permissions are stored in different places,
4010                // so figure out what permission changed and persist the change.
4011                if (permissionsState.getInstallPermissionState(name) != null) {
4012                    scheduleWriteSettingsLocked();
4013                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4014                        || hadState) {
4015                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4016                }
4017            }
4018        }
4019    }
4020
4021    /**
4022     * Update the permission flags for all packages and runtime permissions of a user in order
4023     * to allow device or profile owner to remove POLICY_FIXED.
4024     */
4025    @Override
4026    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4027        if (!sUserManager.exists(userId)) {
4028            return;
4029        }
4030
4031        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4032
4033        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4034                "updatePermissionFlagsForAllApps");
4035
4036        // Only the system can change system fixed flags.
4037        if (getCallingUid() != Process.SYSTEM_UID) {
4038            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4039            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4040        }
4041
4042        synchronized (mPackages) {
4043            boolean changed = false;
4044            final int packageCount = mPackages.size();
4045            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4046                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4047                SettingBase sb = (SettingBase) pkg.mExtras;
4048                if (sb == null) {
4049                    continue;
4050                }
4051                PermissionsState permissionsState = sb.getPermissionsState();
4052                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4053                        userId, flagMask, flagValues);
4054            }
4055            if (changed) {
4056                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4057            }
4058        }
4059    }
4060
4061    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4062        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4063                != PackageManager.PERMISSION_GRANTED
4064            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4065                != PackageManager.PERMISSION_GRANTED) {
4066            throw new SecurityException(message + " requires "
4067                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4068                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4069        }
4070    }
4071
4072    @Override
4073    public boolean shouldShowRequestPermissionRationale(String permissionName,
4074            String packageName, int userId) {
4075        if (UserHandle.getCallingUserId() != userId) {
4076            mContext.enforceCallingPermission(
4077                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4078                    "canShowRequestPermissionRationale for user " + userId);
4079        }
4080
4081        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4082        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4083            return false;
4084        }
4085
4086        if (checkPermission(permissionName, packageName, userId)
4087                == PackageManager.PERMISSION_GRANTED) {
4088            return false;
4089        }
4090
4091        final int flags;
4092
4093        final long identity = Binder.clearCallingIdentity();
4094        try {
4095            flags = getPermissionFlags(permissionName,
4096                    packageName, userId);
4097        } finally {
4098            Binder.restoreCallingIdentity(identity);
4099        }
4100
4101        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4102                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4103                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4104
4105        if ((flags & fixedFlags) != 0) {
4106            return false;
4107        }
4108
4109        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4110    }
4111
4112    @Override
4113    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4114        mContext.enforceCallingOrSelfPermission(
4115                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4116                "addOnPermissionsChangeListener");
4117
4118        synchronized (mPackages) {
4119            mOnPermissionChangeListeners.addListenerLocked(listener);
4120        }
4121    }
4122
4123    @Override
4124    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4125        synchronized (mPackages) {
4126            mOnPermissionChangeListeners.removeListenerLocked(listener);
4127        }
4128    }
4129
4130    @Override
4131    public boolean isProtectedBroadcast(String actionName) {
4132        synchronized (mPackages) {
4133            if (mProtectedBroadcasts.contains(actionName)) {
4134                return true;
4135            } else if (actionName != null) {
4136                // TODO: remove these terrible hacks
4137                if (actionName.startsWith("android.net.netmon.lingerExpired")
4138                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4139                    return true;
4140                }
4141            }
4142        }
4143        return false;
4144    }
4145
4146    @Override
4147    public int checkSignatures(String pkg1, String pkg2) {
4148        synchronized (mPackages) {
4149            final PackageParser.Package p1 = mPackages.get(pkg1);
4150            final PackageParser.Package p2 = mPackages.get(pkg2);
4151            if (p1 == null || p1.mExtras == null
4152                    || p2 == null || p2.mExtras == null) {
4153                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4154            }
4155            return compareSignatures(p1.mSignatures, p2.mSignatures);
4156        }
4157    }
4158
4159    @Override
4160    public int checkUidSignatures(int uid1, int uid2) {
4161        // Map to base uids.
4162        uid1 = UserHandle.getAppId(uid1);
4163        uid2 = UserHandle.getAppId(uid2);
4164        // reader
4165        synchronized (mPackages) {
4166            Signature[] s1;
4167            Signature[] s2;
4168            Object obj = mSettings.getUserIdLPr(uid1);
4169            if (obj != null) {
4170                if (obj instanceof SharedUserSetting) {
4171                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4172                } else if (obj instanceof PackageSetting) {
4173                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4174                } else {
4175                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4176                }
4177            } else {
4178                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4179            }
4180            obj = mSettings.getUserIdLPr(uid2);
4181            if (obj != null) {
4182                if (obj instanceof SharedUserSetting) {
4183                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4184                } else if (obj instanceof PackageSetting) {
4185                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4186                } else {
4187                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4188                }
4189            } else {
4190                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4191            }
4192            return compareSignatures(s1, s2);
4193        }
4194    }
4195
4196    private void killUid(int appId, int userId, String reason) {
4197        final long identity = Binder.clearCallingIdentity();
4198        try {
4199            IActivityManager am = ActivityManagerNative.getDefault();
4200            if (am != null) {
4201                try {
4202                    am.killUid(appId, userId, reason);
4203                } catch (RemoteException e) {
4204                    /* ignore - same process */
4205                }
4206            }
4207        } finally {
4208            Binder.restoreCallingIdentity(identity);
4209        }
4210    }
4211
4212    /**
4213     * Compares two sets of signatures. Returns:
4214     * <br />
4215     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4216     * <br />
4217     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4218     * <br />
4219     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4220     * <br />
4221     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4222     * <br />
4223     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4224     */
4225    static int compareSignatures(Signature[] s1, Signature[] s2) {
4226        if (s1 == null) {
4227            return s2 == null
4228                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4229                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4230        }
4231
4232        if (s2 == null) {
4233            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4234        }
4235
4236        if (s1.length != s2.length) {
4237            return PackageManager.SIGNATURE_NO_MATCH;
4238        }
4239
4240        // Since both signature sets are of size 1, we can compare without HashSets.
4241        if (s1.length == 1) {
4242            return s1[0].equals(s2[0]) ?
4243                    PackageManager.SIGNATURE_MATCH :
4244                    PackageManager.SIGNATURE_NO_MATCH;
4245        }
4246
4247        ArraySet<Signature> set1 = new ArraySet<Signature>();
4248        for (Signature sig : s1) {
4249            set1.add(sig);
4250        }
4251        ArraySet<Signature> set2 = new ArraySet<Signature>();
4252        for (Signature sig : s2) {
4253            set2.add(sig);
4254        }
4255        // Make sure s2 contains all signatures in s1.
4256        if (set1.equals(set2)) {
4257            return PackageManager.SIGNATURE_MATCH;
4258        }
4259        return PackageManager.SIGNATURE_NO_MATCH;
4260    }
4261
4262    /**
4263     * If the database version for this type of package (internal storage or
4264     * external storage) is less than the version where package signatures
4265     * were updated, return true.
4266     */
4267    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4268        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4269        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4270    }
4271
4272    /**
4273     * Used for backward compatibility to make sure any packages with
4274     * certificate chains get upgraded to the new style. {@code existingSigs}
4275     * will be in the old format (since they were stored on disk from before the
4276     * system upgrade) and {@code scannedSigs} will be in the newer format.
4277     */
4278    private int compareSignaturesCompat(PackageSignatures existingSigs,
4279            PackageParser.Package scannedPkg) {
4280        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4281            return PackageManager.SIGNATURE_NO_MATCH;
4282        }
4283
4284        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4285        for (Signature sig : existingSigs.mSignatures) {
4286            existingSet.add(sig);
4287        }
4288        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4289        for (Signature sig : scannedPkg.mSignatures) {
4290            try {
4291                Signature[] chainSignatures = sig.getChainSignatures();
4292                for (Signature chainSig : chainSignatures) {
4293                    scannedCompatSet.add(chainSig);
4294                }
4295            } catch (CertificateEncodingException e) {
4296                scannedCompatSet.add(sig);
4297            }
4298        }
4299        /*
4300         * Make sure the expanded scanned set contains all signatures in the
4301         * existing one.
4302         */
4303        if (scannedCompatSet.equals(existingSet)) {
4304            // Migrate the old signatures to the new scheme.
4305            existingSigs.assignSignatures(scannedPkg.mSignatures);
4306            // The new KeySets will be re-added later in the scanning process.
4307            synchronized (mPackages) {
4308                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4309            }
4310            return PackageManager.SIGNATURE_MATCH;
4311        }
4312        return PackageManager.SIGNATURE_NO_MATCH;
4313    }
4314
4315    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4316        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4317        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4318    }
4319
4320    private int compareSignaturesRecover(PackageSignatures existingSigs,
4321            PackageParser.Package scannedPkg) {
4322        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4323            return PackageManager.SIGNATURE_NO_MATCH;
4324        }
4325
4326        String msg = null;
4327        try {
4328            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4329                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4330                        + scannedPkg.packageName);
4331                return PackageManager.SIGNATURE_MATCH;
4332            }
4333        } catch (CertificateException e) {
4334            msg = e.getMessage();
4335        }
4336
4337        logCriticalInfo(Log.INFO,
4338                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4339        return PackageManager.SIGNATURE_NO_MATCH;
4340    }
4341
4342    @Override
4343    public String[] getPackagesForUid(int uid) {
4344        uid = UserHandle.getAppId(uid);
4345        // reader
4346        synchronized (mPackages) {
4347            Object obj = mSettings.getUserIdLPr(uid);
4348            if (obj instanceof SharedUserSetting) {
4349                final SharedUserSetting sus = (SharedUserSetting) obj;
4350                final int N = sus.packages.size();
4351                final String[] res = new String[N];
4352                final Iterator<PackageSetting> it = sus.packages.iterator();
4353                int i = 0;
4354                while (it.hasNext()) {
4355                    res[i++] = it.next().name;
4356                }
4357                return res;
4358            } else if (obj instanceof PackageSetting) {
4359                final PackageSetting ps = (PackageSetting) obj;
4360                return new String[] { ps.name };
4361            }
4362        }
4363        return null;
4364    }
4365
4366    @Override
4367    public String getNameForUid(int uid) {
4368        // reader
4369        synchronized (mPackages) {
4370            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4371            if (obj instanceof SharedUserSetting) {
4372                final SharedUserSetting sus = (SharedUserSetting) obj;
4373                return sus.name + ":" + sus.userId;
4374            } else if (obj instanceof PackageSetting) {
4375                final PackageSetting ps = (PackageSetting) obj;
4376                return ps.name;
4377            }
4378        }
4379        return null;
4380    }
4381
4382    @Override
4383    public int getUidForSharedUser(String sharedUserName) {
4384        if(sharedUserName == null) {
4385            return -1;
4386        }
4387        // reader
4388        synchronized (mPackages) {
4389            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4390            if (suid == null) {
4391                return -1;
4392            }
4393            return suid.userId;
4394        }
4395    }
4396
4397    @Override
4398    public int getFlagsForUid(int uid) {
4399        synchronized (mPackages) {
4400            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4401            if (obj instanceof SharedUserSetting) {
4402                final SharedUserSetting sus = (SharedUserSetting) obj;
4403                return sus.pkgFlags;
4404            } else if (obj instanceof PackageSetting) {
4405                final PackageSetting ps = (PackageSetting) obj;
4406                return ps.pkgFlags;
4407            }
4408        }
4409        return 0;
4410    }
4411
4412    @Override
4413    public int getPrivateFlagsForUid(int uid) {
4414        synchronized (mPackages) {
4415            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4416            if (obj instanceof SharedUserSetting) {
4417                final SharedUserSetting sus = (SharedUserSetting) obj;
4418                return sus.pkgPrivateFlags;
4419            } else if (obj instanceof PackageSetting) {
4420                final PackageSetting ps = (PackageSetting) obj;
4421                return ps.pkgPrivateFlags;
4422            }
4423        }
4424        return 0;
4425    }
4426
4427    @Override
4428    public boolean isUidPrivileged(int uid) {
4429        uid = UserHandle.getAppId(uid);
4430        // reader
4431        synchronized (mPackages) {
4432            Object obj = mSettings.getUserIdLPr(uid);
4433            if (obj instanceof SharedUserSetting) {
4434                final SharedUserSetting sus = (SharedUserSetting) obj;
4435                final Iterator<PackageSetting> it = sus.packages.iterator();
4436                while (it.hasNext()) {
4437                    if (it.next().isPrivileged()) {
4438                        return true;
4439                    }
4440                }
4441            } else if (obj instanceof PackageSetting) {
4442                final PackageSetting ps = (PackageSetting) obj;
4443                return ps.isPrivileged();
4444            }
4445        }
4446        return false;
4447    }
4448
4449    @Override
4450    public String[] getAppOpPermissionPackages(String permissionName) {
4451        synchronized (mPackages) {
4452            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4453            if (pkgs == null) {
4454                return null;
4455            }
4456            return pkgs.toArray(new String[pkgs.size()]);
4457        }
4458    }
4459
4460    @Override
4461    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4462            int flags, int userId) {
4463        if (!sUserManager.exists(userId)) return null;
4464        flags = updateFlagsForResolve(flags, userId, intent);
4465        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4466        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4467        final ResolveInfo bestChoice =
4468                chooseBestActivity(intent, resolvedType, flags, query, userId);
4469
4470        if (isEphemeralAllowed(intent, query, userId)) {
4471            final EphemeralResolveInfo ai =
4472                    getEphemeralResolveInfo(intent, resolvedType, userId);
4473            if (ai != null) {
4474                if (DEBUG_EPHEMERAL) {
4475                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4476                }
4477                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4478                bestChoice.ephemeralResolveInfo = ai;
4479            }
4480        }
4481        return bestChoice;
4482    }
4483
4484    @Override
4485    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4486            IntentFilter filter, int match, ComponentName activity) {
4487        final int userId = UserHandle.getCallingUserId();
4488        if (DEBUG_PREFERRED) {
4489            Log.v(TAG, "setLastChosenActivity intent=" + intent
4490                + " resolvedType=" + resolvedType
4491                + " flags=" + flags
4492                + " filter=" + filter
4493                + " match=" + match
4494                + " activity=" + activity);
4495            filter.dump(new PrintStreamPrinter(System.out), "    ");
4496        }
4497        intent.setComponent(null);
4498        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4499        // Find any earlier preferred or last chosen entries and nuke them
4500        findPreferredActivity(intent, resolvedType,
4501                flags, query, 0, false, true, false, userId);
4502        // Add the new activity as the last chosen for this filter
4503        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4504                "Setting last chosen");
4505    }
4506
4507    @Override
4508    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4509        final int userId = UserHandle.getCallingUserId();
4510        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4511        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4512        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4513                false, false, false, userId);
4514    }
4515
4516
4517    private boolean isEphemeralAllowed(
4518            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4519        // Short circuit and return early if possible.
4520        if (DISABLE_EPHEMERAL_APPS) {
4521            return false;
4522        }
4523        final int callingUser = UserHandle.getCallingUserId();
4524        if (callingUser != UserHandle.USER_SYSTEM) {
4525            return false;
4526        }
4527        if (mEphemeralResolverConnection == null) {
4528            return false;
4529        }
4530        if (intent.getComponent() != null) {
4531            return false;
4532        }
4533        if (intent.getPackage() != null) {
4534            return false;
4535        }
4536        final boolean isWebUri = hasWebURI(intent);
4537        if (!isWebUri) {
4538            return false;
4539        }
4540        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4541        synchronized (mPackages) {
4542            final int count = resolvedActivites.size();
4543            for (int n = 0; n < count; n++) {
4544                ResolveInfo info = resolvedActivites.get(n);
4545                String packageName = info.activityInfo.packageName;
4546                PackageSetting ps = mSettings.mPackages.get(packageName);
4547                if (ps != null) {
4548                    // Try to get the status from User settings first
4549                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4550                    int status = (int) (packedStatus >> 32);
4551                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4552                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4553                        if (DEBUG_EPHEMERAL) {
4554                            Slog.v(TAG, "DENY ephemeral apps;"
4555                                + " pkg: " + packageName + ", status: " + status);
4556                        }
4557                        return false;
4558                    }
4559                }
4560            }
4561        }
4562        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4563        return true;
4564    }
4565
4566    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4567            int userId) {
4568        MessageDigest digest = null;
4569        try {
4570            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4571        } catch (NoSuchAlgorithmException e) {
4572            // If we can't create a digest, ignore ephemeral apps.
4573            return null;
4574        }
4575
4576        final byte[] hostBytes = intent.getData().getHost().getBytes();
4577        final byte[] digestBytes = digest.digest(hostBytes);
4578        int shaPrefix =
4579                digestBytes[0] << 24
4580                | digestBytes[1] << 16
4581                | digestBytes[2] << 8
4582                | digestBytes[3] << 0;
4583        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4584                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4585        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4586            // No hash prefix match; there are no ephemeral apps for this domain.
4587            return null;
4588        }
4589        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4590            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4591            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4592                continue;
4593            }
4594            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4595            // No filters; this should never happen.
4596            if (filters.isEmpty()) {
4597                continue;
4598            }
4599            // We have a domain match; resolve the filters to see if anything matches.
4600            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4601            for (int j = filters.size() - 1; j >= 0; --j) {
4602                final EphemeralResolveIntentInfo intentInfo =
4603                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4604                ephemeralResolver.addFilter(intentInfo);
4605            }
4606            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4607                    intent, resolvedType, false /*defaultOnly*/, userId);
4608            if (!matchedResolveInfoList.isEmpty()) {
4609                return matchedResolveInfoList.get(0);
4610            }
4611        }
4612        // Hash or filter mis-match; no ephemeral apps for this domain.
4613        return null;
4614    }
4615
4616    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4617            int flags, List<ResolveInfo> query, int userId) {
4618        if (query != null) {
4619            final int N = query.size();
4620            if (N == 1) {
4621                return query.get(0);
4622            } else if (N > 1) {
4623                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4624                // If there is more than one activity with the same priority,
4625                // then let the user decide between them.
4626                ResolveInfo r0 = query.get(0);
4627                ResolveInfo r1 = query.get(1);
4628                if (DEBUG_INTENT_MATCHING || debug) {
4629                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4630                            + r1.activityInfo.name + "=" + r1.priority);
4631                }
4632                // If the first activity has a higher priority, or a different
4633                // default, then it is always desirable to pick it.
4634                if (r0.priority != r1.priority
4635                        || r0.preferredOrder != r1.preferredOrder
4636                        || r0.isDefault != r1.isDefault) {
4637                    return query.get(0);
4638                }
4639                // If we have saved a preference for a preferred activity for
4640                // this Intent, use that.
4641                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4642                        flags, query, r0.priority, true, false, debug, userId);
4643                if (ri != null) {
4644                    return ri;
4645                }
4646                ri = new ResolveInfo(mResolveInfo);
4647                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4648                ri.activityInfo.applicationInfo = new ApplicationInfo(
4649                        ri.activityInfo.applicationInfo);
4650                if (userId != 0) {
4651                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4652                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4653                }
4654                // Make sure that the resolver is displayable in car mode
4655                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4656                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4657                return ri;
4658            }
4659        }
4660        return null;
4661    }
4662
4663    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4664            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4665        final int N = query.size();
4666        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4667                .get(userId);
4668        // Get the list of persistent preferred activities that handle the intent
4669        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4670        List<PersistentPreferredActivity> pprefs = ppir != null
4671                ? ppir.queryIntent(intent, resolvedType,
4672                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4673                : null;
4674        if (pprefs != null && pprefs.size() > 0) {
4675            final int M = pprefs.size();
4676            for (int i=0; i<M; i++) {
4677                final PersistentPreferredActivity ppa = pprefs.get(i);
4678                if (DEBUG_PREFERRED || debug) {
4679                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4680                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4681                            + "\n  component=" + ppa.mComponent);
4682                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4683                }
4684                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4685                        flags | MATCH_DISABLED_COMPONENTS, userId);
4686                if (DEBUG_PREFERRED || debug) {
4687                    Slog.v(TAG, "Found persistent preferred activity:");
4688                    if (ai != null) {
4689                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4690                    } else {
4691                        Slog.v(TAG, "  null");
4692                    }
4693                }
4694                if (ai == null) {
4695                    // This previously registered persistent preferred activity
4696                    // component is no longer known. Ignore it and do NOT remove it.
4697                    continue;
4698                }
4699                for (int j=0; j<N; j++) {
4700                    final ResolveInfo ri = query.get(j);
4701                    if (!ri.activityInfo.applicationInfo.packageName
4702                            .equals(ai.applicationInfo.packageName)) {
4703                        continue;
4704                    }
4705                    if (!ri.activityInfo.name.equals(ai.name)) {
4706                        continue;
4707                    }
4708                    //  Found a persistent preference that can handle the intent.
4709                    if (DEBUG_PREFERRED || debug) {
4710                        Slog.v(TAG, "Returning persistent preferred activity: " +
4711                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4712                    }
4713                    return ri;
4714                }
4715            }
4716        }
4717        return null;
4718    }
4719
4720    // TODO: handle preferred activities missing while user has amnesia
4721    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4722            List<ResolveInfo> query, int priority, boolean always,
4723            boolean removeMatches, boolean debug, int userId) {
4724        if (!sUserManager.exists(userId)) return null;
4725        flags = updateFlagsForResolve(flags, userId, intent);
4726        // writer
4727        synchronized (mPackages) {
4728            if (intent.getSelector() != null) {
4729                intent = intent.getSelector();
4730            }
4731            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4732
4733            // Try to find a matching persistent preferred activity.
4734            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4735                    debug, userId);
4736
4737            // If a persistent preferred activity matched, use it.
4738            if (pri != null) {
4739                return pri;
4740            }
4741
4742            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4743            // Get the list of preferred activities that handle the intent
4744            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4745            List<PreferredActivity> prefs = pir != null
4746                    ? pir.queryIntent(intent, resolvedType,
4747                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4748                    : null;
4749            if (prefs != null && prefs.size() > 0) {
4750                boolean changed = false;
4751                try {
4752                    // First figure out how good the original match set is.
4753                    // We will only allow preferred activities that came
4754                    // from the same match quality.
4755                    int match = 0;
4756
4757                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4758
4759                    final int N = query.size();
4760                    for (int j=0; j<N; j++) {
4761                        final ResolveInfo ri = query.get(j);
4762                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4763                                + ": 0x" + Integer.toHexString(match));
4764                        if (ri.match > match) {
4765                            match = ri.match;
4766                        }
4767                    }
4768
4769                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4770                            + Integer.toHexString(match));
4771
4772                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4773                    final int M = prefs.size();
4774                    for (int i=0; i<M; i++) {
4775                        final PreferredActivity pa = prefs.get(i);
4776                        if (DEBUG_PREFERRED || debug) {
4777                            Slog.v(TAG, "Checking PreferredActivity ds="
4778                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4779                                    + "\n  component=" + pa.mPref.mComponent);
4780                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4781                        }
4782                        if (pa.mPref.mMatch != match) {
4783                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4784                                    + Integer.toHexString(pa.mPref.mMatch));
4785                            continue;
4786                        }
4787                        // If it's not an "always" type preferred activity and that's what we're
4788                        // looking for, skip it.
4789                        if (always && !pa.mPref.mAlways) {
4790                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4791                            continue;
4792                        }
4793                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4794                                flags | MATCH_DISABLED_COMPONENTS, userId);
4795                        if (DEBUG_PREFERRED || debug) {
4796                            Slog.v(TAG, "Found preferred activity:");
4797                            if (ai != null) {
4798                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4799                            } else {
4800                                Slog.v(TAG, "  null");
4801                            }
4802                        }
4803                        if (ai == null) {
4804                            // This previously registered preferred activity
4805                            // component is no longer known.  Most likely an update
4806                            // to the app was installed and in the new version this
4807                            // component no longer exists.  Clean it up by removing
4808                            // it from the preferred activities list, and skip it.
4809                            Slog.w(TAG, "Removing dangling preferred activity: "
4810                                    + pa.mPref.mComponent);
4811                            pir.removeFilter(pa);
4812                            changed = true;
4813                            continue;
4814                        }
4815                        for (int j=0; j<N; j++) {
4816                            final ResolveInfo ri = query.get(j);
4817                            if (!ri.activityInfo.applicationInfo.packageName
4818                                    .equals(ai.applicationInfo.packageName)) {
4819                                continue;
4820                            }
4821                            if (!ri.activityInfo.name.equals(ai.name)) {
4822                                continue;
4823                            }
4824
4825                            if (removeMatches) {
4826                                pir.removeFilter(pa);
4827                                changed = true;
4828                                if (DEBUG_PREFERRED) {
4829                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4830                                }
4831                                break;
4832                            }
4833
4834                            // Okay we found a previously set preferred or last chosen app.
4835                            // If the result set is different from when this
4836                            // was created, we need to clear it and re-ask the
4837                            // user their preference, if we're looking for an "always" type entry.
4838                            if (always && !pa.mPref.sameSet(query)) {
4839                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4840                                        + intent + " type " + resolvedType);
4841                                if (DEBUG_PREFERRED) {
4842                                    Slog.v(TAG, "Removing preferred activity since set changed "
4843                                            + pa.mPref.mComponent);
4844                                }
4845                                pir.removeFilter(pa);
4846                                // Re-add the filter as a "last chosen" entry (!always)
4847                                PreferredActivity lastChosen = new PreferredActivity(
4848                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4849                                pir.addFilter(lastChosen);
4850                                changed = true;
4851                                return null;
4852                            }
4853
4854                            // Yay! Either the set matched or we're looking for the last chosen
4855                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4856                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4857                            return ri;
4858                        }
4859                    }
4860                } finally {
4861                    if (changed) {
4862                        if (DEBUG_PREFERRED) {
4863                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4864                        }
4865                        scheduleWritePackageRestrictionsLocked(userId);
4866                    }
4867                }
4868            }
4869        }
4870        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4871        return null;
4872    }
4873
4874    /*
4875     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4876     */
4877    @Override
4878    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4879            int targetUserId) {
4880        mContext.enforceCallingOrSelfPermission(
4881                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4882        List<CrossProfileIntentFilter> matches =
4883                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4884        if (matches != null) {
4885            int size = matches.size();
4886            for (int i = 0; i < size; i++) {
4887                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4888            }
4889        }
4890        if (hasWebURI(intent)) {
4891            // cross-profile app linking works only towards the parent.
4892            final UserInfo parent = getProfileParent(sourceUserId);
4893            synchronized(mPackages) {
4894                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4895                        intent, resolvedType, 0, sourceUserId, parent.id);
4896                return xpDomainInfo != null;
4897            }
4898        }
4899        return false;
4900    }
4901
4902    private UserInfo getProfileParent(int userId) {
4903        final long identity = Binder.clearCallingIdentity();
4904        try {
4905            return sUserManager.getProfileParent(userId);
4906        } finally {
4907            Binder.restoreCallingIdentity(identity);
4908        }
4909    }
4910
4911    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4912            String resolvedType, int userId) {
4913        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4914        if (resolver != null) {
4915            return resolver.queryIntent(intent, resolvedType, false, userId);
4916        }
4917        return null;
4918    }
4919
4920    @Override
4921    public List<ResolveInfo> queryIntentActivities(Intent intent,
4922            String resolvedType, int flags, int userId) {
4923        if (!sUserManager.exists(userId)) return Collections.emptyList();
4924        flags = updateFlagsForResolve(flags, userId, intent);
4925        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4926        ComponentName comp = intent.getComponent();
4927        if (comp == null) {
4928            if (intent.getSelector() != null) {
4929                intent = intent.getSelector();
4930                comp = intent.getComponent();
4931            }
4932        }
4933
4934        if (comp != null) {
4935            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4936            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4937            if (ai != null) {
4938                final ResolveInfo ri = new ResolveInfo();
4939                ri.activityInfo = ai;
4940                list.add(ri);
4941            }
4942            return list;
4943        }
4944
4945        // reader
4946        synchronized (mPackages) {
4947            final String pkgName = intent.getPackage();
4948            if (pkgName == null) {
4949                List<CrossProfileIntentFilter> matchingFilters =
4950                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4951                // Check for results that need to skip the current profile.
4952                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4953                        resolvedType, flags, userId);
4954                if (xpResolveInfo != null) {
4955                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4956                    result.add(xpResolveInfo);
4957                    return filterIfNotSystemUser(result, userId);
4958                }
4959
4960                // Check for results in the current profile.
4961                List<ResolveInfo> result = mActivities.queryIntent(
4962                        intent, resolvedType, flags, userId);
4963                result = filterIfNotSystemUser(result, userId);
4964
4965                // Check for cross profile results.
4966                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4967                xpResolveInfo = queryCrossProfileIntents(
4968                        matchingFilters, intent, resolvedType, flags, userId,
4969                        hasNonNegativePriorityResult);
4970                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4971                    boolean isVisibleToUser = filterIfNotSystemUser(
4972                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4973                    if (isVisibleToUser) {
4974                        result.add(xpResolveInfo);
4975                        Collections.sort(result, mResolvePrioritySorter);
4976                    }
4977                }
4978                if (hasWebURI(intent)) {
4979                    CrossProfileDomainInfo xpDomainInfo = null;
4980                    final UserInfo parent = getProfileParent(userId);
4981                    if (parent != null) {
4982                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4983                                flags, userId, parent.id);
4984                    }
4985                    if (xpDomainInfo != null) {
4986                        if (xpResolveInfo != null) {
4987                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4988                            // in the result.
4989                            result.remove(xpResolveInfo);
4990                        }
4991                        if (result.size() == 0) {
4992                            result.add(xpDomainInfo.resolveInfo);
4993                            return result;
4994                        }
4995                    } else if (result.size() <= 1) {
4996                        return result;
4997                    }
4998                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4999                            xpDomainInfo, userId);
5000                    Collections.sort(result, mResolvePrioritySorter);
5001                }
5002                return result;
5003            }
5004            final PackageParser.Package pkg = mPackages.get(pkgName);
5005            if (pkg != null) {
5006                return filterIfNotSystemUser(
5007                        mActivities.queryIntentForPackage(
5008                                intent, resolvedType, flags, pkg.activities, userId),
5009                        userId);
5010            }
5011            return new ArrayList<ResolveInfo>();
5012        }
5013    }
5014
5015    private static class CrossProfileDomainInfo {
5016        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5017        ResolveInfo resolveInfo;
5018        /* Best domain verification status of the activities found in the other profile */
5019        int bestDomainVerificationStatus;
5020    }
5021
5022    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5023            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5024        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5025                sourceUserId)) {
5026            return null;
5027        }
5028        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5029                resolvedType, flags, parentUserId);
5030
5031        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5032            return null;
5033        }
5034        CrossProfileDomainInfo result = null;
5035        int size = resultTargetUser.size();
5036        for (int i = 0; i < size; i++) {
5037            ResolveInfo riTargetUser = resultTargetUser.get(i);
5038            // Intent filter verification is only for filters that specify a host. So don't return
5039            // those that handle all web uris.
5040            if (riTargetUser.handleAllWebDataURI) {
5041                continue;
5042            }
5043            String packageName = riTargetUser.activityInfo.packageName;
5044            PackageSetting ps = mSettings.mPackages.get(packageName);
5045            if (ps == null) {
5046                continue;
5047            }
5048            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5049            int status = (int)(verificationState >> 32);
5050            if (result == null) {
5051                result = new CrossProfileDomainInfo();
5052                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5053                        sourceUserId, parentUserId);
5054                result.bestDomainVerificationStatus = status;
5055            } else {
5056                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5057                        result.bestDomainVerificationStatus);
5058            }
5059        }
5060        // Don't consider matches with status NEVER across profiles.
5061        if (result != null && result.bestDomainVerificationStatus
5062                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5063            return null;
5064        }
5065        return result;
5066    }
5067
5068    /**
5069     * Verification statuses are ordered from the worse to the best, except for
5070     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5071     */
5072    private int bestDomainVerificationStatus(int status1, int status2) {
5073        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5074            return status2;
5075        }
5076        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5077            return status1;
5078        }
5079        return (int) MathUtils.max(status1, status2);
5080    }
5081
5082    private boolean isUserEnabled(int userId) {
5083        long callingId = Binder.clearCallingIdentity();
5084        try {
5085            UserInfo userInfo = sUserManager.getUserInfo(userId);
5086            return userInfo != null && userInfo.isEnabled();
5087        } finally {
5088            Binder.restoreCallingIdentity(callingId);
5089        }
5090    }
5091
5092    /**
5093     * Filter out activities with systemUserOnly flag set, when current user is not System.
5094     *
5095     * @return filtered list
5096     */
5097    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5098        if (userId == UserHandle.USER_SYSTEM) {
5099            return resolveInfos;
5100        }
5101        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5102            ResolveInfo info = resolveInfos.get(i);
5103            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5104                resolveInfos.remove(i);
5105            }
5106        }
5107        return resolveInfos;
5108    }
5109
5110    /**
5111     * @param resolveInfos list of resolve infos in descending priority order
5112     * @return if the list contains a resolve info with non-negative priority
5113     */
5114    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5115        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5116    }
5117
5118    private static boolean hasWebURI(Intent intent) {
5119        if (intent.getData() == null) {
5120            return false;
5121        }
5122        final String scheme = intent.getScheme();
5123        if (TextUtils.isEmpty(scheme)) {
5124            return false;
5125        }
5126        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5127    }
5128
5129    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5130            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5131            int userId) {
5132        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5133
5134        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5135            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5136                    candidates.size());
5137        }
5138
5139        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5140        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5141        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5142        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5143        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5144        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5145
5146        synchronized (mPackages) {
5147            final int count = candidates.size();
5148            // First, try to use linked apps. Partition the candidates into four lists:
5149            // one for the final results, one for the "do not use ever", one for "undefined status"
5150            // and finally one for "browser app type".
5151            for (int n=0; n<count; n++) {
5152                ResolveInfo info = candidates.get(n);
5153                String packageName = info.activityInfo.packageName;
5154                PackageSetting ps = mSettings.mPackages.get(packageName);
5155                if (ps != null) {
5156                    // Add to the special match all list (Browser use case)
5157                    if (info.handleAllWebDataURI) {
5158                        matchAllList.add(info);
5159                        continue;
5160                    }
5161                    // Try to get the status from User settings first
5162                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5163                    int status = (int)(packedStatus >> 32);
5164                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5165                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5166                        if (DEBUG_DOMAIN_VERIFICATION) {
5167                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5168                                    + " : linkgen=" + linkGeneration);
5169                        }
5170                        // Use link-enabled generation as preferredOrder, i.e.
5171                        // prefer newly-enabled over earlier-enabled.
5172                        info.preferredOrder = linkGeneration;
5173                        alwaysList.add(info);
5174                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5175                        if (DEBUG_DOMAIN_VERIFICATION) {
5176                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5177                        }
5178                        neverList.add(info);
5179                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5180                        if (DEBUG_DOMAIN_VERIFICATION) {
5181                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5182                        }
5183                        alwaysAskList.add(info);
5184                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5185                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5186                        if (DEBUG_DOMAIN_VERIFICATION) {
5187                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5188                        }
5189                        undefinedList.add(info);
5190                    }
5191                }
5192            }
5193
5194            // We'll want to include browser possibilities in a few cases
5195            boolean includeBrowser = false;
5196
5197            // First try to add the "always" resolution(s) for the current user, if any
5198            if (alwaysList.size() > 0) {
5199                result.addAll(alwaysList);
5200            } else {
5201                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5202                result.addAll(undefinedList);
5203                // Maybe add one for the other profile.
5204                if (xpDomainInfo != null && (
5205                        xpDomainInfo.bestDomainVerificationStatus
5206                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5207                    result.add(xpDomainInfo.resolveInfo);
5208                }
5209                includeBrowser = true;
5210            }
5211
5212            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5213            // If there were 'always' entries their preferred order has been set, so we also
5214            // back that off to make the alternatives equivalent
5215            if (alwaysAskList.size() > 0) {
5216                for (ResolveInfo i : result) {
5217                    i.preferredOrder = 0;
5218                }
5219                result.addAll(alwaysAskList);
5220                includeBrowser = true;
5221            }
5222
5223            if (includeBrowser) {
5224                // Also add browsers (all of them or only the default one)
5225                if (DEBUG_DOMAIN_VERIFICATION) {
5226                    Slog.v(TAG, "   ...including browsers in candidate set");
5227                }
5228                if ((matchFlags & MATCH_ALL) != 0) {
5229                    result.addAll(matchAllList);
5230                } else {
5231                    // Browser/generic handling case.  If there's a default browser, go straight
5232                    // to that (but only if there is no other higher-priority match).
5233                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5234                    int maxMatchPrio = 0;
5235                    ResolveInfo defaultBrowserMatch = null;
5236                    final int numCandidates = matchAllList.size();
5237                    for (int n = 0; n < numCandidates; n++) {
5238                        ResolveInfo info = matchAllList.get(n);
5239                        // track the highest overall match priority...
5240                        if (info.priority > maxMatchPrio) {
5241                            maxMatchPrio = info.priority;
5242                        }
5243                        // ...and the highest-priority default browser match
5244                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5245                            if (defaultBrowserMatch == null
5246                                    || (defaultBrowserMatch.priority < info.priority)) {
5247                                if (debug) {
5248                                    Slog.v(TAG, "Considering default browser match " + info);
5249                                }
5250                                defaultBrowserMatch = info;
5251                            }
5252                        }
5253                    }
5254                    if (defaultBrowserMatch != null
5255                            && defaultBrowserMatch.priority >= maxMatchPrio
5256                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5257                    {
5258                        if (debug) {
5259                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5260                        }
5261                        result.add(defaultBrowserMatch);
5262                    } else {
5263                        result.addAll(matchAllList);
5264                    }
5265                }
5266
5267                // If there is nothing selected, add all candidates and remove the ones that the user
5268                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5269                if (result.size() == 0) {
5270                    result.addAll(candidates);
5271                    result.removeAll(neverList);
5272                }
5273            }
5274        }
5275        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5276            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5277                    result.size());
5278            for (ResolveInfo info : result) {
5279                Slog.v(TAG, "  + " + info.activityInfo);
5280            }
5281        }
5282        return result;
5283    }
5284
5285    // Returns a packed value as a long:
5286    //
5287    // high 'int'-sized word: link status: undefined/ask/never/always.
5288    // low 'int'-sized word: relative priority among 'always' results.
5289    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5290        long result = ps.getDomainVerificationStatusForUser(userId);
5291        // if none available, get the master status
5292        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5293            if (ps.getIntentFilterVerificationInfo() != null) {
5294                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5295            }
5296        }
5297        return result;
5298    }
5299
5300    private ResolveInfo querySkipCurrentProfileIntents(
5301            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5302            int flags, int sourceUserId) {
5303        if (matchingFilters != null) {
5304            int size = matchingFilters.size();
5305            for (int i = 0; i < size; i ++) {
5306                CrossProfileIntentFilter filter = matchingFilters.get(i);
5307                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5308                    // Checking if there are activities in the target user that can handle the
5309                    // intent.
5310                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5311                            resolvedType, flags, sourceUserId);
5312                    if (resolveInfo != null) {
5313                        return resolveInfo;
5314                    }
5315                }
5316            }
5317        }
5318        return null;
5319    }
5320
5321    // Return matching ResolveInfo in target user if any.
5322    private ResolveInfo queryCrossProfileIntents(
5323            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5324            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5325        if (matchingFilters != null) {
5326            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5327            // match the same intent. For performance reasons, it is better not to
5328            // run queryIntent twice for the same userId
5329            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5330            int size = matchingFilters.size();
5331            for (int i = 0; i < size; i++) {
5332                CrossProfileIntentFilter filter = matchingFilters.get(i);
5333                int targetUserId = filter.getTargetUserId();
5334                boolean skipCurrentProfile =
5335                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5336                boolean skipCurrentProfileIfNoMatchFound =
5337                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5338                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5339                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5340                    // Checking if there are activities in the target user that can handle the
5341                    // intent.
5342                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5343                            resolvedType, flags, sourceUserId);
5344                    if (resolveInfo != null) return resolveInfo;
5345                    alreadyTriedUserIds.put(targetUserId, true);
5346                }
5347            }
5348        }
5349        return null;
5350    }
5351
5352    /**
5353     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5354     * will forward the intent to the filter's target user.
5355     * Otherwise, returns null.
5356     */
5357    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5358            String resolvedType, int flags, int sourceUserId) {
5359        int targetUserId = filter.getTargetUserId();
5360        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5361                resolvedType, flags, targetUserId);
5362        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5363                && isUserEnabled(targetUserId)) {
5364            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5365        }
5366        return null;
5367    }
5368
5369    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5370            int sourceUserId, int targetUserId) {
5371        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5372        long ident = Binder.clearCallingIdentity();
5373        boolean targetIsProfile;
5374        try {
5375            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5376        } finally {
5377            Binder.restoreCallingIdentity(ident);
5378        }
5379        String className;
5380        if (targetIsProfile) {
5381            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5382        } else {
5383            className = FORWARD_INTENT_TO_PARENT;
5384        }
5385        ComponentName forwardingActivityComponentName = new ComponentName(
5386                mAndroidApplication.packageName, className);
5387        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5388                sourceUserId);
5389        if (!targetIsProfile) {
5390            forwardingActivityInfo.showUserIcon = targetUserId;
5391            forwardingResolveInfo.noResourceId = true;
5392        }
5393        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5394        forwardingResolveInfo.priority = 0;
5395        forwardingResolveInfo.preferredOrder = 0;
5396        forwardingResolveInfo.match = 0;
5397        forwardingResolveInfo.isDefault = true;
5398        forwardingResolveInfo.filter = filter;
5399        forwardingResolveInfo.targetUserId = targetUserId;
5400        return forwardingResolveInfo;
5401    }
5402
5403    @Override
5404    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5405            Intent[] specifics, String[] specificTypes, Intent intent,
5406            String resolvedType, int flags, int userId) {
5407        if (!sUserManager.exists(userId)) return Collections.emptyList();
5408        flags = updateFlagsForResolve(flags, userId, intent);
5409        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5410                false, "query intent activity options");
5411        final String resultsAction = intent.getAction();
5412
5413        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5414                | PackageManager.GET_RESOLVED_FILTER, userId);
5415
5416        if (DEBUG_INTENT_MATCHING) {
5417            Log.v(TAG, "Query " + intent + ": " + results);
5418        }
5419
5420        int specificsPos = 0;
5421        int N;
5422
5423        // todo: note that the algorithm used here is O(N^2).  This
5424        // isn't a problem in our current environment, but if we start running
5425        // into situations where we have more than 5 or 10 matches then this
5426        // should probably be changed to something smarter...
5427
5428        // First we go through and resolve each of the specific items
5429        // that were supplied, taking care of removing any corresponding
5430        // duplicate items in the generic resolve list.
5431        if (specifics != null) {
5432            for (int i=0; i<specifics.length; i++) {
5433                final Intent sintent = specifics[i];
5434                if (sintent == null) {
5435                    continue;
5436                }
5437
5438                if (DEBUG_INTENT_MATCHING) {
5439                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5440                }
5441
5442                String action = sintent.getAction();
5443                if (resultsAction != null && resultsAction.equals(action)) {
5444                    // If this action was explicitly requested, then don't
5445                    // remove things that have it.
5446                    action = null;
5447                }
5448
5449                ResolveInfo ri = null;
5450                ActivityInfo ai = null;
5451
5452                ComponentName comp = sintent.getComponent();
5453                if (comp == null) {
5454                    ri = resolveIntent(
5455                        sintent,
5456                        specificTypes != null ? specificTypes[i] : null,
5457                            flags, userId);
5458                    if (ri == null) {
5459                        continue;
5460                    }
5461                    if (ri == mResolveInfo) {
5462                        // ACK!  Must do something better with this.
5463                    }
5464                    ai = ri.activityInfo;
5465                    comp = new ComponentName(ai.applicationInfo.packageName,
5466                            ai.name);
5467                } else {
5468                    ai = getActivityInfo(comp, flags, userId);
5469                    if (ai == null) {
5470                        continue;
5471                    }
5472                }
5473
5474                // Look for any generic query activities that are duplicates
5475                // of this specific one, and remove them from the results.
5476                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5477                N = results.size();
5478                int j;
5479                for (j=specificsPos; j<N; j++) {
5480                    ResolveInfo sri = results.get(j);
5481                    if ((sri.activityInfo.name.equals(comp.getClassName())
5482                            && sri.activityInfo.applicationInfo.packageName.equals(
5483                                    comp.getPackageName()))
5484                        || (action != null && sri.filter.matchAction(action))) {
5485                        results.remove(j);
5486                        if (DEBUG_INTENT_MATCHING) Log.v(
5487                            TAG, "Removing duplicate item from " + j
5488                            + " due to specific " + specificsPos);
5489                        if (ri == null) {
5490                            ri = sri;
5491                        }
5492                        j--;
5493                        N--;
5494                    }
5495                }
5496
5497                // Add this specific item to its proper place.
5498                if (ri == null) {
5499                    ri = new ResolveInfo();
5500                    ri.activityInfo = ai;
5501                }
5502                results.add(specificsPos, ri);
5503                ri.specificIndex = i;
5504                specificsPos++;
5505            }
5506        }
5507
5508        // Now we go through the remaining generic results and remove any
5509        // duplicate actions that are found here.
5510        N = results.size();
5511        for (int i=specificsPos; i<N-1; i++) {
5512            final ResolveInfo rii = results.get(i);
5513            if (rii.filter == null) {
5514                continue;
5515            }
5516
5517            // Iterate over all of the actions of this result's intent
5518            // filter...  typically this should be just one.
5519            final Iterator<String> it = rii.filter.actionsIterator();
5520            if (it == null) {
5521                continue;
5522            }
5523            while (it.hasNext()) {
5524                final String action = it.next();
5525                if (resultsAction != null && resultsAction.equals(action)) {
5526                    // If this action was explicitly requested, then don't
5527                    // remove things that have it.
5528                    continue;
5529                }
5530                for (int j=i+1; j<N; j++) {
5531                    final ResolveInfo rij = results.get(j);
5532                    if (rij.filter != null && rij.filter.hasAction(action)) {
5533                        results.remove(j);
5534                        if (DEBUG_INTENT_MATCHING) Log.v(
5535                            TAG, "Removing duplicate item from " + j
5536                            + " due to action " + action + " at " + i);
5537                        j--;
5538                        N--;
5539                    }
5540                }
5541            }
5542
5543            // If the caller didn't request filter information, drop it now
5544            // so we don't have to marshall/unmarshall it.
5545            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5546                rii.filter = null;
5547            }
5548        }
5549
5550        // Filter out the caller activity if so requested.
5551        if (caller != null) {
5552            N = results.size();
5553            for (int i=0; i<N; i++) {
5554                ActivityInfo ainfo = results.get(i).activityInfo;
5555                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5556                        && caller.getClassName().equals(ainfo.name)) {
5557                    results.remove(i);
5558                    break;
5559                }
5560            }
5561        }
5562
5563        // If the caller didn't request filter information,
5564        // drop them now so we don't have to
5565        // marshall/unmarshall it.
5566        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5567            N = results.size();
5568            for (int i=0; i<N; i++) {
5569                results.get(i).filter = null;
5570            }
5571        }
5572
5573        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5574        return results;
5575    }
5576
5577    @Override
5578    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5579            int userId) {
5580        if (!sUserManager.exists(userId)) return Collections.emptyList();
5581        flags = updateFlagsForResolve(flags, userId, intent);
5582        ComponentName comp = intent.getComponent();
5583        if (comp == null) {
5584            if (intent.getSelector() != null) {
5585                intent = intent.getSelector();
5586                comp = intent.getComponent();
5587            }
5588        }
5589        if (comp != null) {
5590            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5591            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5592            if (ai != null) {
5593                ResolveInfo ri = new ResolveInfo();
5594                ri.activityInfo = ai;
5595                list.add(ri);
5596            }
5597            return list;
5598        }
5599
5600        // reader
5601        synchronized (mPackages) {
5602            String pkgName = intent.getPackage();
5603            if (pkgName == null) {
5604                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5605            }
5606            final PackageParser.Package pkg = mPackages.get(pkgName);
5607            if (pkg != null) {
5608                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5609                        userId);
5610            }
5611            return null;
5612        }
5613    }
5614
5615    @Override
5616    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5617        if (!sUserManager.exists(userId)) return null;
5618        flags = updateFlagsForResolve(flags, userId, intent);
5619        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5620        if (query != null) {
5621            if (query.size() >= 1) {
5622                // If there is more than one service with the same priority,
5623                // just arbitrarily pick the first one.
5624                return query.get(0);
5625            }
5626        }
5627        return null;
5628    }
5629
5630    @Override
5631    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5632            int userId) {
5633        if (!sUserManager.exists(userId)) return Collections.emptyList();
5634        flags = updateFlagsForResolve(flags, userId, intent);
5635        ComponentName comp = intent.getComponent();
5636        if (comp == null) {
5637            if (intent.getSelector() != null) {
5638                intent = intent.getSelector();
5639                comp = intent.getComponent();
5640            }
5641        }
5642        if (comp != null) {
5643            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5644            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5645            if (si != null) {
5646                final ResolveInfo ri = new ResolveInfo();
5647                ri.serviceInfo = si;
5648                list.add(ri);
5649            }
5650            return list;
5651        }
5652
5653        // reader
5654        synchronized (mPackages) {
5655            String pkgName = intent.getPackage();
5656            if (pkgName == null) {
5657                return mServices.queryIntent(intent, resolvedType, flags, userId);
5658            }
5659            final PackageParser.Package pkg = mPackages.get(pkgName);
5660            if (pkg != null) {
5661                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5662                        userId);
5663            }
5664            return null;
5665        }
5666    }
5667
5668    @Override
5669    public List<ResolveInfo> queryIntentContentProviders(
5670            Intent intent, String resolvedType, int flags, int userId) {
5671        if (!sUserManager.exists(userId)) return Collections.emptyList();
5672        flags = updateFlagsForResolve(flags, userId, intent);
5673        ComponentName comp = intent.getComponent();
5674        if (comp == null) {
5675            if (intent.getSelector() != null) {
5676                intent = intent.getSelector();
5677                comp = intent.getComponent();
5678            }
5679        }
5680        if (comp != null) {
5681            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5682            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5683            if (pi != null) {
5684                final ResolveInfo ri = new ResolveInfo();
5685                ri.providerInfo = pi;
5686                list.add(ri);
5687            }
5688            return list;
5689        }
5690
5691        // reader
5692        synchronized (mPackages) {
5693            String pkgName = intent.getPackage();
5694            if (pkgName == null) {
5695                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5696            }
5697            final PackageParser.Package pkg = mPackages.get(pkgName);
5698            if (pkg != null) {
5699                return mProviders.queryIntentForPackage(
5700                        intent, resolvedType, flags, pkg.providers, userId);
5701            }
5702            return null;
5703        }
5704    }
5705
5706    @Override
5707    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5708        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5709        flags = updateFlagsForPackage(flags, userId, null);
5710        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5711        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5712
5713        // writer
5714        synchronized (mPackages) {
5715            ArrayList<PackageInfo> list;
5716            if (listUninstalled) {
5717                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5718                for (PackageSetting ps : mSettings.mPackages.values()) {
5719                    PackageInfo pi;
5720                    if (ps.pkg != null) {
5721                        pi = generatePackageInfo(ps.pkg, flags, userId);
5722                    } else {
5723                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5724                    }
5725                    if (pi != null) {
5726                        list.add(pi);
5727                    }
5728                }
5729            } else {
5730                list = new ArrayList<PackageInfo>(mPackages.size());
5731                for (PackageParser.Package p : mPackages.values()) {
5732                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5733                    if (pi != null) {
5734                        list.add(pi);
5735                    }
5736                }
5737            }
5738
5739            return new ParceledListSlice<PackageInfo>(list);
5740        }
5741    }
5742
5743    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5744            String[] permissions, boolean[] tmp, int flags, int userId) {
5745        int numMatch = 0;
5746        final PermissionsState permissionsState = ps.getPermissionsState();
5747        for (int i=0; i<permissions.length; i++) {
5748            final String permission = permissions[i];
5749            if (permissionsState.hasPermission(permission, userId)) {
5750                tmp[i] = true;
5751                numMatch++;
5752            } else {
5753                tmp[i] = false;
5754            }
5755        }
5756        if (numMatch == 0) {
5757            return;
5758        }
5759        PackageInfo pi;
5760        if (ps.pkg != null) {
5761            pi = generatePackageInfo(ps.pkg, flags, userId);
5762        } else {
5763            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5764        }
5765        // The above might return null in cases of uninstalled apps or install-state
5766        // skew across users/profiles.
5767        if (pi != null) {
5768            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5769                if (numMatch == permissions.length) {
5770                    pi.requestedPermissions = permissions;
5771                } else {
5772                    pi.requestedPermissions = new String[numMatch];
5773                    numMatch = 0;
5774                    for (int i=0; i<permissions.length; i++) {
5775                        if (tmp[i]) {
5776                            pi.requestedPermissions[numMatch] = permissions[i];
5777                            numMatch++;
5778                        }
5779                    }
5780                }
5781            }
5782            list.add(pi);
5783        }
5784    }
5785
5786    @Override
5787    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5788            String[] permissions, int flags, int userId) {
5789        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5790        flags = updateFlagsForPackage(flags, userId, permissions);
5791        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5792
5793        // writer
5794        synchronized (mPackages) {
5795            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5796            boolean[] tmpBools = new boolean[permissions.length];
5797            if (listUninstalled) {
5798                for (PackageSetting ps : mSettings.mPackages.values()) {
5799                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5800                }
5801            } else {
5802                for (PackageParser.Package pkg : mPackages.values()) {
5803                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5804                    if (ps != null) {
5805                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5806                                userId);
5807                    }
5808                }
5809            }
5810
5811            return new ParceledListSlice<PackageInfo>(list);
5812        }
5813    }
5814
5815    @Override
5816    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5817        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5818        flags = updateFlagsForApplication(flags, userId, null);
5819        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5820
5821        // writer
5822        synchronized (mPackages) {
5823            ArrayList<ApplicationInfo> list;
5824            if (listUninstalled) {
5825                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5826                for (PackageSetting ps : mSettings.mPackages.values()) {
5827                    ApplicationInfo ai;
5828                    if (ps.pkg != null) {
5829                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5830                                ps.readUserState(userId), userId);
5831                    } else {
5832                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5833                    }
5834                    if (ai != null) {
5835                        list.add(ai);
5836                    }
5837                }
5838            } else {
5839                list = new ArrayList<ApplicationInfo>(mPackages.size());
5840                for (PackageParser.Package p : mPackages.values()) {
5841                    if (p.mExtras != null) {
5842                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5843                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5844                        if (ai != null) {
5845                            list.add(ai);
5846                        }
5847                    }
5848                }
5849            }
5850
5851            return new ParceledListSlice<ApplicationInfo>(list);
5852        }
5853    }
5854
5855    @Override
5856    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5857        if (DISABLE_EPHEMERAL_APPS) {
5858            return null;
5859        }
5860
5861        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5862                "getEphemeralApplications");
5863        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5864                "getEphemeralApplications");
5865        synchronized (mPackages) {
5866            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5867                    .getEphemeralApplicationsLPw(userId);
5868            if (ephemeralApps != null) {
5869                return new ParceledListSlice<>(ephemeralApps);
5870            }
5871        }
5872        return null;
5873    }
5874
5875    @Override
5876    public boolean isEphemeralApplication(String packageName, int userId) {
5877        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5878                "isEphemeral");
5879        if (DISABLE_EPHEMERAL_APPS) {
5880            return false;
5881        }
5882
5883        if (!isCallerSameApp(packageName)) {
5884            return false;
5885        }
5886        synchronized (mPackages) {
5887            PackageParser.Package pkg = mPackages.get(packageName);
5888            if (pkg != null) {
5889                return pkg.applicationInfo.isEphemeralApp();
5890            }
5891        }
5892        return false;
5893    }
5894
5895    @Override
5896    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5897        if (DISABLE_EPHEMERAL_APPS) {
5898            return null;
5899        }
5900
5901        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5902                "getCookie");
5903        if (!isCallerSameApp(packageName)) {
5904            return null;
5905        }
5906        synchronized (mPackages) {
5907            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5908                    packageName, userId);
5909        }
5910    }
5911
5912    @Override
5913    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5914        if (DISABLE_EPHEMERAL_APPS) {
5915            return true;
5916        }
5917
5918        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5919                "setCookie");
5920        if (!isCallerSameApp(packageName)) {
5921            return false;
5922        }
5923        synchronized (mPackages) {
5924            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5925                    packageName, cookie, userId);
5926        }
5927    }
5928
5929    @Override
5930    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5931        if (DISABLE_EPHEMERAL_APPS) {
5932            return null;
5933        }
5934
5935        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5936                "getEphemeralApplicationIcon");
5937        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5938                "getEphemeralApplicationIcon");
5939        synchronized (mPackages) {
5940            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5941                    packageName, userId);
5942        }
5943    }
5944
5945    private boolean isCallerSameApp(String packageName) {
5946        PackageParser.Package pkg = mPackages.get(packageName);
5947        return pkg != null
5948                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5949    }
5950
5951    public List<ApplicationInfo> getPersistentApplications(int flags) {
5952        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5953
5954        // reader
5955        synchronized (mPackages) {
5956            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5957            final int userId = UserHandle.getCallingUserId();
5958            while (i.hasNext()) {
5959                final PackageParser.Package p = i.next();
5960                if (p.applicationInfo != null
5961                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5962                        && (!mSafeMode || isSystemApp(p))) {
5963                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5964                    if (ps != null) {
5965                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5966                                ps.readUserState(userId), userId);
5967                        if (ai != null) {
5968                            finalList.add(ai);
5969                        }
5970                    }
5971                }
5972            }
5973        }
5974
5975        return finalList;
5976    }
5977
5978    @Override
5979    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5980        if (!sUserManager.exists(userId)) return null;
5981        flags = updateFlagsForComponent(flags, userId, name);
5982        // reader
5983        synchronized (mPackages) {
5984            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5985            PackageSetting ps = provider != null
5986                    ? mSettings.mPackages.get(provider.owner.packageName)
5987                    : null;
5988            return ps != null
5989                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5990                    ? PackageParser.generateProviderInfo(provider, flags,
5991                            ps.readUserState(userId), userId)
5992                    : null;
5993        }
5994    }
5995
5996    /**
5997     * @deprecated
5998     */
5999    @Deprecated
6000    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6001        // reader
6002        synchronized (mPackages) {
6003            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6004                    .entrySet().iterator();
6005            final int userId = UserHandle.getCallingUserId();
6006            while (i.hasNext()) {
6007                Map.Entry<String, PackageParser.Provider> entry = i.next();
6008                PackageParser.Provider p = entry.getValue();
6009                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6010
6011                if (ps != null && p.syncable
6012                        && (!mSafeMode || (p.info.applicationInfo.flags
6013                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6014                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6015                            ps.readUserState(userId), userId);
6016                    if (info != null) {
6017                        outNames.add(entry.getKey());
6018                        outInfo.add(info);
6019                    }
6020                }
6021            }
6022        }
6023    }
6024
6025    @Override
6026    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6027            int uid, int flags) {
6028        final int userId = processName != null ? UserHandle.getUserId(uid)
6029                : UserHandle.getCallingUserId();
6030        if (!sUserManager.exists(userId)) return null;
6031        flags = updateFlagsForComponent(flags, userId, processName);
6032
6033        ArrayList<ProviderInfo> finalList = null;
6034        // reader
6035        synchronized (mPackages) {
6036            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6037            while (i.hasNext()) {
6038                final PackageParser.Provider p = i.next();
6039                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6040                if (ps != null && p.info.authority != null
6041                        && (processName == null
6042                                || (p.info.processName.equals(processName)
6043                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6044                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6045                    if (finalList == null) {
6046                        finalList = new ArrayList<ProviderInfo>(3);
6047                    }
6048                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6049                            ps.readUserState(userId), userId);
6050                    if (info != null) {
6051                        finalList.add(info);
6052                    }
6053                }
6054            }
6055        }
6056
6057        if (finalList != null) {
6058            Collections.sort(finalList, mProviderInitOrderSorter);
6059            return new ParceledListSlice<ProviderInfo>(finalList);
6060        }
6061
6062        return null;
6063    }
6064
6065    @Override
6066    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6067        // reader
6068        synchronized (mPackages) {
6069            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6070            return PackageParser.generateInstrumentationInfo(i, flags);
6071        }
6072    }
6073
6074    @Override
6075    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6076            int flags) {
6077        ArrayList<InstrumentationInfo> finalList =
6078            new ArrayList<InstrumentationInfo>();
6079
6080        // reader
6081        synchronized (mPackages) {
6082            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6083            while (i.hasNext()) {
6084                final PackageParser.Instrumentation p = i.next();
6085                if (targetPackage == null
6086                        || targetPackage.equals(p.info.targetPackage)) {
6087                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6088                            flags);
6089                    if (ii != null) {
6090                        finalList.add(ii);
6091                    }
6092                }
6093            }
6094        }
6095
6096        return finalList;
6097    }
6098
6099    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6100        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6101        if (overlays == null) {
6102            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6103            return;
6104        }
6105        for (PackageParser.Package opkg : overlays.values()) {
6106            // Not much to do if idmap fails: we already logged the error
6107            // and we certainly don't want to abort installation of pkg simply
6108            // because an overlay didn't fit properly. For these reasons,
6109            // ignore the return value of createIdmapForPackagePairLI.
6110            createIdmapForPackagePairLI(pkg, opkg);
6111        }
6112    }
6113
6114    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6115            PackageParser.Package opkg) {
6116        if (!opkg.mTrustedOverlay) {
6117            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6118                    opkg.baseCodePath + ": overlay not trusted");
6119            return false;
6120        }
6121        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6122        if (overlaySet == null) {
6123            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6124                    opkg.baseCodePath + " but target package has no known overlays");
6125            return false;
6126        }
6127        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6128        // TODO: generate idmap for split APKs
6129        try {
6130            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6131        } catch (InstallerException e) {
6132            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6133                    + opkg.baseCodePath);
6134            return false;
6135        }
6136        PackageParser.Package[] overlayArray =
6137            overlaySet.values().toArray(new PackageParser.Package[0]);
6138        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6139            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6140                return p1.mOverlayPriority - p2.mOverlayPriority;
6141            }
6142        };
6143        Arrays.sort(overlayArray, cmp);
6144
6145        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6146        int i = 0;
6147        for (PackageParser.Package p : overlayArray) {
6148            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6149        }
6150        return true;
6151    }
6152
6153    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6154        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6155        try {
6156            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6157        } finally {
6158            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6159        }
6160    }
6161
6162    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6163        final File[] files = dir.listFiles();
6164        if (ArrayUtils.isEmpty(files)) {
6165            Log.d(TAG, "No files in app dir " + dir);
6166            return;
6167        }
6168
6169        if (DEBUG_PACKAGE_SCANNING) {
6170            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6171                    + " flags=0x" + Integer.toHexString(parseFlags));
6172        }
6173
6174        for (File file : files) {
6175            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6176                    && !PackageInstallerService.isStageName(file.getName());
6177            if (!isPackage) {
6178                // Ignore entries which are not packages
6179                continue;
6180            }
6181            try {
6182                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6183                        scanFlags, currentTime, null);
6184            } catch (PackageManagerException e) {
6185                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6186
6187                // Delete invalid userdata apps
6188                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6189                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6190                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6191                    removeCodePathLI(file);
6192                }
6193            }
6194        }
6195    }
6196
6197    private static File getSettingsProblemFile() {
6198        File dataDir = Environment.getDataDirectory();
6199        File systemDir = new File(dataDir, "system");
6200        File fname = new File(systemDir, "uiderrors.txt");
6201        return fname;
6202    }
6203
6204    static void reportSettingsProblem(int priority, String msg) {
6205        logCriticalInfo(priority, msg);
6206    }
6207
6208    static void logCriticalInfo(int priority, String msg) {
6209        Slog.println(priority, TAG, msg);
6210        EventLogTags.writePmCriticalInfo(msg);
6211        try {
6212            File fname = getSettingsProblemFile();
6213            FileOutputStream out = new FileOutputStream(fname, true);
6214            PrintWriter pw = new FastPrintWriter(out);
6215            SimpleDateFormat formatter = new SimpleDateFormat();
6216            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6217            pw.println(dateString + ": " + msg);
6218            pw.close();
6219            FileUtils.setPermissions(
6220                    fname.toString(),
6221                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6222                    -1, -1);
6223        } catch (java.io.IOException e) {
6224        }
6225    }
6226
6227    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6228            PackageParser.Package pkg, File srcFile, int parseFlags)
6229            throws PackageManagerException {
6230        if (ps != null
6231                && ps.codePath.equals(srcFile)
6232                && ps.timeStamp == srcFile.lastModified()
6233                && !isCompatSignatureUpdateNeeded(pkg)
6234                && !isRecoverSignatureUpdateNeeded(pkg)) {
6235            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6236            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6237            ArraySet<PublicKey> signingKs;
6238            synchronized (mPackages) {
6239                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6240            }
6241            if (ps.signatures.mSignatures != null
6242                    && ps.signatures.mSignatures.length != 0
6243                    && signingKs != null) {
6244                // Optimization: reuse the existing cached certificates
6245                // if the package appears to be unchanged.
6246                pkg.mSignatures = ps.signatures.mSignatures;
6247                pkg.mSigningKeys = signingKs;
6248                return;
6249            }
6250
6251            Slog.w(TAG, "PackageSetting for " + ps.name
6252                    + " is missing signatures.  Collecting certs again to recover them.");
6253        } else {
6254            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6255        }
6256
6257        try {
6258            pp.collectCertificates(pkg, parseFlags);
6259        } catch (PackageParserException e) {
6260            throw PackageManagerException.from(e);
6261        }
6262    }
6263
6264    /**
6265     *  Traces a package scan.
6266     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6267     */
6268    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6269            long currentTime, UserHandle user) throws PackageManagerException {
6270        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6271        try {
6272            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6273        } finally {
6274            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6275        }
6276    }
6277
6278    /**
6279     *  Scans a package and returns the newly parsed package.
6280     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6281     */
6282    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6283            long currentTime, UserHandle user) throws PackageManagerException {
6284        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6285        parseFlags |= mDefParseFlags;
6286        PackageParser pp = new PackageParser();
6287        pp.setSeparateProcesses(mSeparateProcesses);
6288        pp.setOnlyCoreApps(mOnlyCore);
6289        pp.setDisplayMetrics(mMetrics);
6290
6291        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6292            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6293        }
6294
6295        final PackageParser.Package pkg;
6296        try {
6297            pkg = pp.parsePackage(scanFile, parseFlags);
6298        } catch (PackageParserException e) {
6299            throw PackageManagerException.from(e);
6300        }
6301
6302        PackageSetting ps = null;
6303        PackageSetting updatedPkg;
6304        // reader
6305        synchronized (mPackages) {
6306            // Look to see if we already know about this package.
6307            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6308            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6309                // This package has been renamed to its original name.  Let's
6310                // use that.
6311                ps = mSettings.peekPackageLPr(oldName);
6312            }
6313            // If there was no original package, see one for the real package name.
6314            if (ps == null) {
6315                ps = mSettings.peekPackageLPr(pkg.packageName);
6316            }
6317            // Check to see if this package could be hiding/updating a system
6318            // package.  Must look for it either under the original or real
6319            // package name depending on our state.
6320            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6321            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6322        }
6323        boolean updatedPkgBetter = false;
6324        // First check if this is a system package that may involve an update
6325        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6326            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6327            // it needs to drop FLAG_PRIVILEGED.
6328            if (locationIsPrivileged(scanFile)) {
6329                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6330            } else {
6331                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6332            }
6333
6334            if (ps != null && !ps.codePath.equals(scanFile)) {
6335                // The path has changed from what was last scanned...  check the
6336                // version of the new path against what we have stored to determine
6337                // what to do.
6338                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6339                if (pkg.mVersionCode <= ps.versionCode) {
6340                    // The system package has been updated and the code path does not match
6341                    // Ignore entry. Skip it.
6342                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6343                            + " ignored: updated version " + ps.versionCode
6344                            + " better than this " + pkg.mVersionCode);
6345                    if (!updatedPkg.codePath.equals(scanFile)) {
6346                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6347                                + ps.name + " changing from " + updatedPkg.codePathString
6348                                + " to " + scanFile);
6349                        updatedPkg.codePath = scanFile;
6350                        updatedPkg.codePathString = scanFile.toString();
6351                        updatedPkg.resourcePath = scanFile;
6352                        updatedPkg.resourcePathString = scanFile.toString();
6353                    }
6354                    updatedPkg.pkg = pkg;
6355                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6356                            "Package " + ps.name + " at " + scanFile
6357                                    + " ignored: updated version " + ps.versionCode
6358                                    + " better than this " + pkg.mVersionCode);
6359                } else {
6360                    // The current app on the system partition is better than
6361                    // what we have updated to on the data partition; switch
6362                    // back to the system partition version.
6363                    // At this point, its safely assumed that package installation for
6364                    // apps in system partition will go through. If not there won't be a working
6365                    // version of the app
6366                    // writer
6367                    synchronized (mPackages) {
6368                        // Just remove the loaded entries from package lists.
6369                        mPackages.remove(ps.name);
6370                    }
6371
6372                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6373                            + " reverting from " + ps.codePathString
6374                            + ": new version " + pkg.mVersionCode
6375                            + " better than installed " + ps.versionCode);
6376
6377                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6378                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6379                    synchronized (mInstallLock) {
6380                        args.cleanUpResourcesLI();
6381                    }
6382                    synchronized (mPackages) {
6383                        mSettings.enableSystemPackageLPw(ps.name);
6384                    }
6385                    updatedPkgBetter = true;
6386                }
6387            }
6388        }
6389
6390        if (updatedPkg != null) {
6391            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6392            // initially
6393            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6394
6395            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6396            // flag set initially
6397            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6398                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6399            }
6400        }
6401
6402        // Verify certificates against what was last scanned
6403        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6404
6405        /*
6406         * A new system app appeared, but we already had a non-system one of the
6407         * same name installed earlier.
6408         */
6409        boolean shouldHideSystemApp = false;
6410        if (updatedPkg == null && ps != null
6411                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6412            /*
6413             * Check to make sure the signatures match first. If they don't,
6414             * wipe the installed application and its data.
6415             */
6416            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6417                    != PackageManager.SIGNATURE_MATCH) {
6418                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6419                        + " signatures don't match existing userdata copy; removing");
6420                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6421                ps = null;
6422            } else {
6423                /*
6424                 * If the newly-added system app is an older version than the
6425                 * already installed version, hide it. It will be scanned later
6426                 * and re-added like an update.
6427                 */
6428                if (pkg.mVersionCode <= ps.versionCode) {
6429                    shouldHideSystemApp = true;
6430                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6431                            + " but new version " + pkg.mVersionCode + " better than installed "
6432                            + ps.versionCode + "; hiding system");
6433                } else {
6434                    /*
6435                     * The newly found system app is a newer version that the
6436                     * one previously installed. Simply remove the
6437                     * already-installed application and replace it with our own
6438                     * while keeping the application data.
6439                     */
6440                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6441                            + " reverting from " + ps.codePathString + ": new version "
6442                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6443                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6444                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6445                    synchronized (mInstallLock) {
6446                        args.cleanUpResourcesLI();
6447                    }
6448                }
6449            }
6450        }
6451
6452        // The apk is forward locked (not public) if its code and resources
6453        // are kept in different files. (except for app in either system or
6454        // vendor path).
6455        // TODO grab this value from PackageSettings
6456        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6457            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6458                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6459            }
6460        }
6461
6462        // TODO: extend to support forward-locked splits
6463        String resourcePath = null;
6464        String baseResourcePath = null;
6465        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6466            if (ps != null && ps.resourcePathString != null) {
6467                resourcePath = ps.resourcePathString;
6468                baseResourcePath = ps.resourcePathString;
6469            } else {
6470                // Should not happen at all. Just log an error.
6471                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6472            }
6473        } else {
6474            resourcePath = pkg.codePath;
6475            baseResourcePath = pkg.baseCodePath;
6476        }
6477
6478        // Set application objects path explicitly.
6479        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6480        pkg.applicationInfo.setCodePath(pkg.codePath);
6481        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6482        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6483        pkg.applicationInfo.setResourcePath(resourcePath);
6484        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6485        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6486
6487        // Note that we invoke the following method only if we are about to unpack an application
6488        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6489                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6490
6491        /*
6492         * If the system app should be overridden by a previously installed
6493         * data, hide the system app now and let the /data/app scan pick it up
6494         * again.
6495         */
6496        if (shouldHideSystemApp) {
6497            synchronized (mPackages) {
6498                mSettings.disableSystemPackageLPw(pkg.packageName);
6499            }
6500        }
6501
6502        return scannedPkg;
6503    }
6504
6505    private static String fixProcessName(String defProcessName,
6506            String processName, int uid) {
6507        if (processName == null) {
6508            return defProcessName;
6509        }
6510        return processName;
6511    }
6512
6513    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6514            throws PackageManagerException {
6515        if (pkgSetting.signatures.mSignatures != null) {
6516            // Already existing package. Make sure signatures match
6517            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6518                    == PackageManager.SIGNATURE_MATCH;
6519            if (!match) {
6520                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6521                        == PackageManager.SIGNATURE_MATCH;
6522            }
6523            if (!match) {
6524                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6525                        == PackageManager.SIGNATURE_MATCH;
6526            }
6527            if (!match) {
6528                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6529                        + pkg.packageName + " signatures do not match the "
6530                        + "previously installed version; ignoring!");
6531            }
6532        }
6533
6534        // Check for shared user signatures
6535        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6536            // Already existing package. Make sure signatures match
6537            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6538                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6539            if (!match) {
6540                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6541                        == PackageManager.SIGNATURE_MATCH;
6542            }
6543            if (!match) {
6544                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6545                        == PackageManager.SIGNATURE_MATCH;
6546            }
6547            if (!match) {
6548                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6549                        "Package " + pkg.packageName
6550                        + " has no signatures that match those in shared user "
6551                        + pkgSetting.sharedUser.name + "; ignoring!");
6552            }
6553        }
6554    }
6555
6556    /**
6557     * Enforces that only the system UID or root's UID can call a method exposed
6558     * via Binder.
6559     *
6560     * @param message used as message if SecurityException is thrown
6561     * @throws SecurityException if the caller is not system or root
6562     */
6563    private static final void enforceSystemOrRoot(String message) {
6564        final int uid = Binder.getCallingUid();
6565        if (uid != Process.SYSTEM_UID && uid != 0) {
6566            throw new SecurityException(message);
6567        }
6568    }
6569
6570    @Override
6571    public void performFstrimIfNeeded() {
6572        enforceSystemOrRoot("Only the system can request fstrim");
6573
6574        // Before everything else, see whether we need to fstrim.
6575        try {
6576            IMountService ms = PackageHelper.getMountService();
6577            if (ms != null) {
6578                final boolean isUpgrade = isUpgrade();
6579                boolean doTrim = isUpgrade;
6580                if (doTrim) {
6581                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6582                } else {
6583                    final long interval = android.provider.Settings.Global.getLong(
6584                            mContext.getContentResolver(),
6585                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6586                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6587                    if (interval > 0) {
6588                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6589                        if (timeSinceLast > interval) {
6590                            doTrim = true;
6591                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6592                                    + "; running immediately");
6593                        }
6594                    }
6595                }
6596                if (doTrim) {
6597                    if (!isFirstBoot()) {
6598                        try {
6599                            ActivityManagerNative.getDefault().showBootMessage(
6600                                    mContext.getResources().getString(
6601                                            R.string.android_upgrading_fstrim), true);
6602                        } catch (RemoteException e) {
6603                        }
6604                    }
6605                    ms.runMaintenance();
6606                }
6607            } else {
6608                Slog.e(TAG, "Mount service unavailable!");
6609            }
6610        } catch (RemoteException e) {
6611            // Can't happen; MountService is local
6612        }
6613    }
6614
6615    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6616        List<ResolveInfo> ris = null;
6617        try {
6618            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6619                    intent, null, 0, userId);
6620        } catch (RemoteException e) {
6621        }
6622        ArraySet<String> pkgNames = new ArraySet<String>();
6623        if (ris != null) {
6624            for (ResolveInfo ri : ris) {
6625                pkgNames.add(ri.activityInfo.packageName);
6626            }
6627        }
6628        return pkgNames;
6629    }
6630
6631    @Override
6632    public void notifyPackageUse(String packageName) {
6633        synchronized (mPackages) {
6634            PackageParser.Package p = mPackages.get(packageName);
6635            if (p == null) {
6636                return;
6637            }
6638            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6639        }
6640    }
6641
6642    @Override
6643    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6644        return performDexOptTraced(packageName, instructionSet);
6645    }
6646
6647    public boolean performDexOpt(String packageName, String instructionSet) {
6648        return performDexOptTraced(packageName, instructionSet);
6649    }
6650
6651    private boolean performDexOptTraced(String packageName, String instructionSet) {
6652        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6653        try {
6654            return performDexOptInternal(packageName, instructionSet);
6655        } finally {
6656            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6657        }
6658    }
6659
6660    private boolean performDexOptInternal(String packageName, String instructionSet) {
6661        PackageParser.Package p;
6662        final String targetInstructionSet;
6663        synchronized (mPackages) {
6664            p = mPackages.get(packageName);
6665            if (p == null) {
6666                return false;
6667            }
6668            mPackageUsage.write(false);
6669
6670            targetInstructionSet = instructionSet != null ? instructionSet :
6671                    getPrimaryInstructionSet(p.applicationInfo);
6672            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6673                return false;
6674            }
6675        }
6676        long callingId = Binder.clearCallingIdentity();
6677        try {
6678            synchronized (mInstallLock) {
6679                final String[] instructionSets = new String[] { targetInstructionSet };
6680                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6681                        true /* inclDependencies */);
6682                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6683            }
6684        } finally {
6685            Binder.restoreCallingIdentity(callingId);
6686        }
6687    }
6688
6689    public ArraySet<String> getPackagesThatNeedDexOpt() {
6690        ArraySet<String> pkgs = null;
6691        synchronized (mPackages) {
6692            for (PackageParser.Package p : mPackages.values()) {
6693                if (DEBUG_DEXOPT) {
6694                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6695                }
6696                if (!p.mDexOptPerformed.isEmpty()) {
6697                    continue;
6698                }
6699                if (pkgs == null) {
6700                    pkgs = new ArraySet<String>();
6701                }
6702                pkgs.add(p.packageName);
6703            }
6704        }
6705        return pkgs;
6706    }
6707
6708    public void shutdown() {
6709        mPackageUsage.write(true);
6710    }
6711
6712    @Override
6713    public void forceDexOpt(String packageName) {
6714        enforceSystemOrRoot("forceDexOpt");
6715
6716        PackageParser.Package pkg;
6717        synchronized (mPackages) {
6718            pkg = mPackages.get(packageName);
6719            if (pkg == null) {
6720                throw new IllegalArgumentException("Unknown package: " + packageName);
6721            }
6722        }
6723
6724        synchronized (mInstallLock) {
6725            final String[] instructionSets = new String[] {
6726                    getPrimaryInstructionSet(pkg.applicationInfo) };
6727
6728            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6729
6730            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6731                    true /* inclDependencies */);
6732
6733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6734            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6735                throw new IllegalStateException("Failed to dexopt: " + res);
6736            }
6737        }
6738    }
6739
6740    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6741        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6742            Slog.w(TAG, "Unable to update from " + oldPkg.name
6743                    + " to " + newPkg.packageName
6744                    + ": old package not in system partition");
6745            return false;
6746        } else if (mPackages.get(oldPkg.name) != null) {
6747            Slog.w(TAG, "Unable to update from " + oldPkg.name
6748                    + " to " + newPkg.packageName
6749                    + ": old package still exists");
6750            return false;
6751        }
6752        return true;
6753    }
6754
6755    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6756            throws PackageManagerException {
6757        // TODO: triage flags as part of 26466827
6758        final int appId = UserHandle.getAppId(uid);
6759        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6760
6761        try {
6762            final int[] users = sUserManager.getUserIds();
6763            for (int user : users) {
6764                mInstaller.createAppData(volumeUuid, packageName, user, flags, appId, seinfo);
6765            }
6766        } catch (InstallerException e) {
6767            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6768                    "Failed to prepare data directory", e);
6769        }
6770    }
6771
6772    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6773        // TODO: triage flags as part of 26466827
6774        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6775
6776        boolean res = true;
6777        final int[] users = sUserManager.getUserIds();
6778        for (int user : users) {
6779            try {
6780                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6781            } catch (InstallerException e) {
6782                Slog.w(TAG, "Failed to delete data directory", e);
6783                res = false;
6784            }
6785        }
6786        return res;
6787    }
6788
6789    void removeCodePathLI(File codePath) {
6790        if (codePath.isDirectory()) {
6791            try {
6792                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6793            } catch (InstallerException e) {
6794                Slog.w(TAG, "Failed to remove code path", e);
6795            }
6796        } else {
6797            codePath.delete();
6798        }
6799    }
6800
6801    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6802        // TODO: triage flags as part of 26466827
6803        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6804
6805        final int[] users = sUserManager.getUserIds();
6806        for (int user : users) {
6807            try {
6808                mInstaller.clearAppData(volumeUuid, packageName, user,
6809                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6810            } catch (InstallerException e) {
6811                Slog.w(TAG, "Failed to delete code cache directory", e);
6812            }
6813        }
6814    }
6815
6816    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6817            PackageParser.Package changingLib) {
6818        if (file.path != null) {
6819            usesLibraryFiles.add(file.path);
6820            return;
6821        }
6822        PackageParser.Package p = mPackages.get(file.apk);
6823        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6824            // If we are doing this while in the middle of updating a library apk,
6825            // then we need to make sure to use that new apk for determining the
6826            // dependencies here.  (We haven't yet finished committing the new apk
6827            // to the package manager state.)
6828            if (p == null || p.packageName.equals(changingLib.packageName)) {
6829                p = changingLib;
6830            }
6831        }
6832        if (p != null) {
6833            usesLibraryFiles.addAll(p.getAllCodePaths());
6834        }
6835    }
6836
6837    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6838            PackageParser.Package changingLib) throws PackageManagerException {
6839        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6840            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6841            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6842            for (int i=0; i<N; i++) {
6843                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6844                if (file == null) {
6845                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6846                            "Package " + pkg.packageName + " requires unavailable shared library "
6847                            + pkg.usesLibraries.get(i) + "; failing!");
6848                }
6849                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6850            }
6851            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6852            for (int i=0; i<N; i++) {
6853                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6854                if (file == null) {
6855                    Slog.w(TAG, "Package " + pkg.packageName
6856                            + " desires unavailable shared library "
6857                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6858                } else {
6859                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6860                }
6861            }
6862            N = usesLibraryFiles.size();
6863            if (N > 0) {
6864                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6865            } else {
6866                pkg.usesLibraryFiles = null;
6867            }
6868        }
6869    }
6870
6871    private static boolean hasString(List<String> list, List<String> which) {
6872        if (list == null) {
6873            return false;
6874        }
6875        for (int i=list.size()-1; i>=0; i--) {
6876            for (int j=which.size()-1; j>=0; j--) {
6877                if (which.get(j).equals(list.get(i))) {
6878                    return true;
6879                }
6880            }
6881        }
6882        return false;
6883    }
6884
6885    private void updateAllSharedLibrariesLPw() {
6886        for (PackageParser.Package pkg : mPackages.values()) {
6887            try {
6888                updateSharedLibrariesLPw(pkg, null);
6889            } catch (PackageManagerException e) {
6890                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6891            }
6892        }
6893    }
6894
6895    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6896            PackageParser.Package changingPkg) {
6897        ArrayList<PackageParser.Package> res = null;
6898        for (PackageParser.Package pkg : mPackages.values()) {
6899            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6900                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6901                if (res == null) {
6902                    res = new ArrayList<PackageParser.Package>();
6903                }
6904                res.add(pkg);
6905                try {
6906                    updateSharedLibrariesLPw(pkg, changingPkg);
6907                } catch (PackageManagerException e) {
6908                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6909                }
6910            }
6911        }
6912        return res;
6913    }
6914
6915    /**
6916     * Derive the value of the {@code cpuAbiOverride} based on the provided
6917     * value and an optional stored value from the package settings.
6918     */
6919    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6920        String cpuAbiOverride = null;
6921
6922        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6923            cpuAbiOverride = null;
6924        } else if (abiOverride != null) {
6925            cpuAbiOverride = abiOverride;
6926        } else if (settings != null) {
6927            cpuAbiOverride = settings.cpuAbiOverrideString;
6928        }
6929
6930        return cpuAbiOverride;
6931    }
6932
6933    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6934            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6935        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6936        try {
6937            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6938        } finally {
6939            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6940        }
6941    }
6942
6943    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6944            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6945        boolean success = false;
6946        try {
6947            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6948                    currentTime, user);
6949            success = true;
6950            return res;
6951        } finally {
6952            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6953                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6954            }
6955        }
6956    }
6957
6958    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6959            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6960        final File scanFile = new File(pkg.codePath);
6961        if (pkg.applicationInfo.getCodePath() == null ||
6962                pkg.applicationInfo.getResourcePath() == null) {
6963            // Bail out. The resource and code paths haven't been set.
6964            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6965                    "Code and resource paths haven't been set correctly");
6966        }
6967
6968        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6969            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6970        } else {
6971            // Only allow system apps to be flagged as core apps.
6972            pkg.coreApp = false;
6973        }
6974
6975        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6976            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6977        }
6978
6979        if (mCustomResolverComponentName != null &&
6980                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6981            setUpCustomResolverActivity(pkg);
6982        }
6983
6984        if (pkg.packageName.equals("android")) {
6985            synchronized (mPackages) {
6986                if (mAndroidApplication != null) {
6987                    Slog.w(TAG, "*************************************************");
6988                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6989                    Slog.w(TAG, " file=" + scanFile);
6990                    Slog.w(TAG, "*************************************************");
6991                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6992                            "Core android package being redefined.  Skipping.");
6993                }
6994
6995                // Set up information for our fall-back user intent resolution activity.
6996                mPlatformPackage = pkg;
6997                pkg.mVersionCode = mSdkVersion;
6998                mAndroidApplication = pkg.applicationInfo;
6999
7000                if (!mResolverReplaced) {
7001                    mResolveActivity.applicationInfo = mAndroidApplication;
7002                    mResolveActivity.name = ResolverActivity.class.getName();
7003                    mResolveActivity.packageName = mAndroidApplication.packageName;
7004                    mResolveActivity.processName = "system:ui";
7005                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7006                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7007                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7008                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7009                    mResolveActivity.exported = true;
7010                    mResolveActivity.enabled = true;
7011                    mResolveInfo.activityInfo = mResolveActivity;
7012                    mResolveInfo.priority = 0;
7013                    mResolveInfo.preferredOrder = 0;
7014                    mResolveInfo.match = 0;
7015                    mResolveComponentName = new ComponentName(
7016                            mAndroidApplication.packageName, mResolveActivity.name);
7017                }
7018            }
7019        }
7020
7021        if (DEBUG_PACKAGE_SCANNING) {
7022            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7023                Log.d(TAG, "Scanning package " + pkg.packageName);
7024        }
7025
7026        if (mPackages.containsKey(pkg.packageName)
7027                || mSharedLibraries.containsKey(pkg.packageName)) {
7028            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7029                    "Application package " + pkg.packageName
7030                    + " already installed.  Skipping duplicate.");
7031        }
7032
7033        // If we're only installing presumed-existing packages, require that the
7034        // scanned APK is both already known and at the path previously established
7035        // for it.  Previously unknown packages we pick up normally, but if we have an
7036        // a priori expectation about this package's install presence, enforce it.
7037        // With a singular exception for new system packages. When an OTA contains
7038        // a new system package, we allow the codepath to change from a system location
7039        // to the user-installed location. If we don't allow this change, any newer,
7040        // user-installed version of the application will be ignored.
7041        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7042            if (mExpectingBetter.containsKey(pkg.packageName)) {
7043                logCriticalInfo(Log.WARN,
7044                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7045            } else {
7046                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7047                if (known != null) {
7048                    if (DEBUG_PACKAGE_SCANNING) {
7049                        Log.d(TAG, "Examining " + pkg.codePath
7050                                + " and requiring known paths " + known.codePathString
7051                                + " & " + known.resourcePathString);
7052                    }
7053                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7054                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7055                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7056                                "Application package " + pkg.packageName
7057                                + " found at " + pkg.applicationInfo.getCodePath()
7058                                + " but expected at " + known.codePathString + "; ignoring.");
7059                    }
7060                }
7061            }
7062        }
7063
7064        // Initialize package source and resource directories
7065        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7066        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7067
7068        SharedUserSetting suid = null;
7069        PackageSetting pkgSetting = null;
7070
7071        if (!isSystemApp(pkg)) {
7072            // Only system apps can use these features.
7073            pkg.mOriginalPackages = null;
7074            pkg.mRealPackage = null;
7075            pkg.mAdoptPermissions = null;
7076        }
7077
7078        // writer
7079        synchronized (mPackages) {
7080            if (pkg.mSharedUserId != null) {
7081                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7082                if (suid == null) {
7083                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7084                            "Creating application package " + pkg.packageName
7085                            + " for shared user failed");
7086                }
7087                if (DEBUG_PACKAGE_SCANNING) {
7088                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7089                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7090                                + "): packages=" + suid.packages);
7091                }
7092            }
7093
7094            // Check if we are renaming from an original package name.
7095            PackageSetting origPackage = null;
7096            String realName = null;
7097            if (pkg.mOriginalPackages != null) {
7098                // This package may need to be renamed to a previously
7099                // installed name.  Let's check on that...
7100                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7101                if (pkg.mOriginalPackages.contains(renamed)) {
7102                    // This package had originally been installed as the
7103                    // original name, and we have already taken care of
7104                    // transitioning to the new one.  Just update the new
7105                    // one to continue using the old name.
7106                    realName = pkg.mRealPackage;
7107                    if (!pkg.packageName.equals(renamed)) {
7108                        // Callers into this function may have already taken
7109                        // care of renaming the package; only do it here if
7110                        // it is not already done.
7111                        pkg.setPackageName(renamed);
7112                    }
7113
7114                } else {
7115                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7116                        if ((origPackage = mSettings.peekPackageLPr(
7117                                pkg.mOriginalPackages.get(i))) != null) {
7118                            // We do have the package already installed under its
7119                            // original name...  should we use it?
7120                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7121                                // New package is not compatible with original.
7122                                origPackage = null;
7123                                continue;
7124                            } else if (origPackage.sharedUser != null) {
7125                                // Make sure uid is compatible between packages.
7126                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7127                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7128                                            + " to " + pkg.packageName + ": old uid "
7129                                            + origPackage.sharedUser.name
7130                                            + " differs from " + pkg.mSharedUserId);
7131                                    origPackage = null;
7132                                    continue;
7133                                }
7134                            } else {
7135                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7136                                        + pkg.packageName + " to old name " + origPackage.name);
7137                            }
7138                            break;
7139                        }
7140                    }
7141                }
7142            }
7143
7144            if (mTransferedPackages.contains(pkg.packageName)) {
7145                Slog.w(TAG, "Package " + pkg.packageName
7146                        + " was transferred to another, but its .apk remains");
7147            }
7148
7149            // Just create the setting, don't add it yet. For already existing packages
7150            // the PkgSetting exists already and doesn't have to be created.
7151            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7152                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7153                    pkg.applicationInfo.primaryCpuAbi,
7154                    pkg.applicationInfo.secondaryCpuAbi,
7155                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7156                    user, false);
7157            if (pkgSetting == null) {
7158                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7159                        "Creating application package " + pkg.packageName + " failed");
7160            }
7161
7162            if (pkgSetting.origPackage != null) {
7163                // If we are first transitioning from an original package,
7164                // fix up the new package's name now.  We need to do this after
7165                // looking up the package under its new name, so getPackageLP
7166                // can take care of fiddling things correctly.
7167                pkg.setPackageName(origPackage.name);
7168
7169                // File a report about this.
7170                String msg = "New package " + pkgSetting.realName
7171                        + " renamed to replace old package " + pkgSetting.name;
7172                reportSettingsProblem(Log.WARN, msg);
7173
7174                // Make a note of it.
7175                mTransferedPackages.add(origPackage.name);
7176
7177                // No longer need to retain this.
7178                pkgSetting.origPackage = null;
7179            }
7180
7181            if (realName != null) {
7182                // Make a note of it.
7183                mTransferedPackages.add(pkg.packageName);
7184            }
7185
7186            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7187                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7188            }
7189
7190            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7191                // Check all shared libraries and map to their actual file path.
7192                // We only do this here for apps not on a system dir, because those
7193                // are the only ones that can fail an install due to this.  We
7194                // will take care of the system apps by updating all of their
7195                // library paths after the scan is done.
7196                updateSharedLibrariesLPw(pkg, null);
7197            }
7198
7199            if (mFoundPolicyFile) {
7200                SELinuxMMAC.assignSeinfoValue(pkg);
7201            }
7202
7203            pkg.applicationInfo.uid = pkgSetting.appId;
7204            pkg.mExtras = pkgSetting;
7205            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7206                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7207                    // We just determined the app is signed correctly, so bring
7208                    // over the latest parsed certs.
7209                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7210                } else {
7211                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7212                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7213                                "Package " + pkg.packageName + " upgrade keys do not match the "
7214                                + "previously installed version");
7215                    } else {
7216                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7217                        String msg = "System package " + pkg.packageName
7218                            + " signature changed; retaining data.";
7219                        reportSettingsProblem(Log.WARN, msg);
7220                    }
7221                }
7222            } else {
7223                try {
7224                    verifySignaturesLP(pkgSetting, pkg);
7225                    // We just determined the app is signed correctly, so bring
7226                    // over the latest parsed certs.
7227                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7228                } catch (PackageManagerException e) {
7229                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7230                        throw e;
7231                    }
7232                    // The signature has changed, but this package is in the system
7233                    // image...  let's recover!
7234                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7235                    // However...  if this package is part of a shared user, but it
7236                    // doesn't match the signature of the shared user, let's fail.
7237                    // What this means is that you can't change the signatures
7238                    // associated with an overall shared user, which doesn't seem all
7239                    // that unreasonable.
7240                    if (pkgSetting.sharedUser != null) {
7241                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7242                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7243                            throw new PackageManagerException(
7244                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7245                                            "Signature mismatch for shared user: "
7246                                            + pkgSetting.sharedUser);
7247                        }
7248                    }
7249                    // File a report about this.
7250                    String msg = "System package " + pkg.packageName
7251                        + " signature changed; retaining data.";
7252                    reportSettingsProblem(Log.WARN, msg);
7253                }
7254            }
7255            // Verify that this new package doesn't have any content providers
7256            // that conflict with existing packages.  Only do this if the
7257            // package isn't already installed, since we don't want to break
7258            // things that are installed.
7259            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7260                final int N = pkg.providers.size();
7261                int i;
7262                for (i=0; i<N; i++) {
7263                    PackageParser.Provider p = pkg.providers.get(i);
7264                    if (p.info.authority != null) {
7265                        String names[] = p.info.authority.split(";");
7266                        for (int j = 0; j < names.length; j++) {
7267                            if (mProvidersByAuthority.containsKey(names[j])) {
7268                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7269                                final String otherPackageName =
7270                                        ((other != null && other.getComponentName() != null) ?
7271                                                other.getComponentName().getPackageName() : "?");
7272                                throw new PackageManagerException(
7273                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7274                                                "Can't install because provider name " + names[j]
7275                                                + " (in package " + pkg.applicationInfo.packageName
7276                                                + ") is already used by " + otherPackageName);
7277                            }
7278                        }
7279                    }
7280                }
7281            }
7282
7283            if (pkg.mAdoptPermissions != null) {
7284                // This package wants to adopt ownership of permissions from
7285                // another package.
7286                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7287                    final String origName = pkg.mAdoptPermissions.get(i);
7288                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7289                    if (orig != null) {
7290                        if (verifyPackageUpdateLPr(orig, pkg)) {
7291                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7292                                    + pkg.packageName);
7293                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7294                        }
7295                    }
7296                }
7297            }
7298        }
7299
7300        final String pkgName = pkg.packageName;
7301
7302        final long scanFileTime = scanFile.lastModified();
7303        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7304        pkg.applicationInfo.processName = fixProcessName(
7305                pkg.applicationInfo.packageName,
7306                pkg.applicationInfo.processName,
7307                pkg.applicationInfo.uid);
7308
7309        if (pkg != mPlatformPackage) {
7310            // This is a normal package, need to make its data directory.
7311            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7312                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7313
7314            // TOOD: switch to ensure various directories
7315
7316            boolean uidError = false;
7317            if (dataPath.exists()) {
7318                int currentUid = 0;
7319                try {
7320                    StructStat stat = Os.stat(dataPath.getPath());
7321                    currentUid = stat.st_uid;
7322                } catch (ErrnoException e) {
7323                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7324                }
7325
7326                // If we have mismatched owners for the data path, we have a problem.
7327                if (currentUid != pkg.applicationInfo.uid) {
7328                    boolean recovered = false;
7329                    if (((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0
7330                            || (scanFlags & SCAN_BOOTING) != 0)) {
7331                        // If this is a system app, we can at least delete its
7332                        // current data so the application will still work.
7333                        boolean res = removeDataDirsLI(pkg.volumeUuid, pkgName);
7334                        if (res) {
7335                            // TODO: Kill the processes first
7336                            // Old data gone!
7337                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7338                                    ? "System package " : "Third party package ";
7339                            String msg = prefix + pkg.packageName
7340                                    + " has changed from uid: "
7341                                    + currentUid + " to "
7342                                    + pkg.applicationInfo.uid + "; old data erased";
7343                            reportSettingsProblem(Log.WARN, msg);
7344                            recovered = true;
7345                        }
7346                        if (!recovered) {
7347                            mHasSystemUidErrors = true;
7348                        }
7349                    } else {
7350                        // If we allow this install to proceed, we will be broken.
7351                        // Abort, abort!
7352                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7353                                "Expected data to be owned by UID " + pkg.applicationInfo.uid
7354                                        + " but found " + currentUid);
7355                    }
7356                    if (!recovered) {
7357                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7358                            + pkg.applicationInfo.uid + "/fs_"
7359                            + currentUid;
7360                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7361                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7362                        String msg = "Package " + pkg.packageName
7363                                + " has mismatched uid: "
7364                                + currentUid + " on disk, "
7365                                + pkg.applicationInfo.uid + " in settings";
7366                        // writer
7367                        synchronized (mPackages) {
7368                            mSettings.mReadMessages.append(msg);
7369                            mSettings.mReadMessages.append('\n');
7370                            uidError = true;
7371                            if (!pkgSetting.uidError) {
7372                                reportSettingsProblem(Log.ERROR, msg);
7373                            }
7374                        }
7375                    }
7376                }
7377
7378                // Ensure that directories are prepared
7379                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7380                        pkg.applicationInfo.seinfo);
7381
7382                if (mShouldRestoreconData) {
7383                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7384                    // TODO: extend this to restorecon over all users
7385                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
7386                    // TODO: triage flags as part of 26466827
7387                    final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
7388                    try {
7389                        mInstaller.restoreconAppData(pkg.volumeUuid, pkg.packageName,
7390                                UserHandle.USER_SYSTEM, flags, appId, pkg.applicationInfo.seinfo);
7391                    } catch (InstallerException e) {
7392                        Slog.w(TAG, "Failed to restorecon " + pkg.packageName, e);
7393                    }
7394                }
7395            } else {
7396                if (DEBUG_PACKAGE_SCANNING) {
7397                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7398                        Log.v(TAG, "Want this data dir: " + dataPath);
7399                }
7400                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7401                        pkg.applicationInfo.seinfo);
7402            }
7403
7404            // Get all of our default paths setup
7405            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7406
7407            pkgSetting.uidError = uidError;
7408        }
7409
7410        final String path = scanFile.getPath();
7411        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7412
7413        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7414            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7415
7416            // Some system apps still use directory structure for native libraries
7417            // in which case we might end up not detecting abi solely based on apk
7418            // structure. Try to detect abi based on directory structure.
7419            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7420                    pkg.applicationInfo.primaryCpuAbi == null) {
7421                setBundledAppAbisAndRoots(pkg, pkgSetting);
7422                setNativeLibraryPaths(pkg);
7423            }
7424
7425        } else {
7426            if ((scanFlags & SCAN_MOVE) != 0) {
7427                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7428                // but we already have this packages package info in the PackageSetting. We just
7429                // use that and derive the native library path based on the new codepath.
7430                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7431                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7432            }
7433
7434            // Set native library paths again. For moves, the path will be updated based on the
7435            // ABIs we've determined above. For non-moves, the path will be updated based on the
7436            // ABIs we determined during compilation, but the path will depend on the final
7437            // package path (after the rename away from the stage path).
7438            setNativeLibraryPaths(pkg);
7439        }
7440
7441        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7442        final int[] userIds = sUserManager.getUserIds();
7443        synchronized (mInstallLock) {
7444            // Make sure all user data directories are ready to roll; we're okay
7445            // if they already exist
7446            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7447                for (int userId : userIds) {
7448                    if (userId != UserHandle.USER_SYSTEM) {
7449                        // TODO: triage flags as part of 26466827
7450                        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
7451                        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
7452                        try {
7453                            mInstaller.createAppData(pkg.volumeUuid, pkg.packageName, userId,
7454                                    flags, appId, pkg.applicationInfo.seinfo);
7455                        } catch (InstallerException e) {
7456                            throw PackageManagerException.from(e);
7457                        }
7458                    }
7459                }
7460            }
7461
7462            // Create a native library symlink only if we have native libraries
7463            // and if the native libraries are 32 bit libraries. We do not provide
7464            // this symlink for 64 bit libraries.
7465            if (pkg.applicationInfo.primaryCpuAbi != null &&
7466                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7467                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7468                try {
7469                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7470                    for (int userId : userIds) {
7471                        try {
7472                            mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7473                                    nativeLibPath, userId);
7474                        } catch (InstallerException e) {
7475                            throw PackageManagerException.from(e);
7476                        }
7477                    }
7478                } finally {
7479                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7480                }
7481            }
7482        }
7483
7484        // This is a special case for the "system" package, where the ABI is
7485        // dictated by the zygote configuration (and init.rc). We should keep track
7486        // of this ABI so that we can deal with "normal" applications that run under
7487        // the same UID correctly.
7488        if (mPlatformPackage == pkg) {
7489            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7490                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7491        }
7492
7493        // If there's a mismatch between the abi-override in the package setting
7494        // and the abiOverride specified for the install. Warn about this because we
7495        // would've already compiled the app without taking the package setting into
7496        // account.
7497        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7498            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7499                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7500                        " for package " + pkg.packageName);
7501            }
7502        }
7503
7504        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7505        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7506        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7507
7508        // Copy the derived override back to the parsed package, so that we can
7509        // update the package settings accordingly.
7510        pkg.cpuAbiOverride = cpuAbiOverride;
7511
7512        if (DEBUG_ABI_SELECTION) {
7513            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7514                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7515                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7516        }
7517
7518        // Push the derived path down into PackageSettings so we know what to
7519        // clean up at uninstall time.
7520        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7521
7522        if (DEBUG_ABI_SELECTION) {
7523            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7524                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7525                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7526        }
7527
7528        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7529            // We don't do this here during boot because we can do it all
7530            // at once after scanning all existing packages.
7531            //
7532            // We also do this *before* we perform dexopt on this package, so that
7533            // we can avoid redundant dexopts, and also to make sure we've got the
7534            // code and package path correct.
7535            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7536                    pkg, true /* boot complete */);
7537        }
7538
7539        if (mFactoryTest && pkg.requestedPermissions.contains(
7540                android.Manifest.permission.FACTORY_TEST)) {
7541            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7542        }
7543
7544        ArrayList<PackageParser.Package> clientLibPkgs = null;
7545
7546        // writer
7547        synchronized (mPackages) {
7548            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7549                // Only system apps can add new shared libraries.
7550                if (pkg.libraryNames != null) {
7551                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7552                        String name = pkg.libraryNames.get(i);
7553                        boolean allowed = false;
7554                        if (pkg.isUpdatedSystemApp()) {
7555                            // New library entries can only be added through the
7556                            // system image.  This is important to get rid of a lot
7557                            // of nasty edge cases: for example if we allowed a non-
7558                            // system update of the app to add a library, then uninstalling
7559                            // the update would make the library go away, and assumptions
7560                            // we made such as through app install filtering would now
7561                            // have allowed apps on the device which aren't compatible
7562                            // with it.  Better to just have the restriction here, be
7563                            // conservative, and create many fewer cases that can negatively
7564                            // impact the user experience.
7565                            final PackageSetting sysPs = mSettings
7566                                    .getDisabledSystemPkgLPr(pkg.packageName);
7567                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7568                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7569                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7570                                        allowed = true;
7571                                        break;
7572                                    }
7573                                }
7574                            }
7575                        } else {
7576                            allowed = true;
7577                        }
7578                        if (allowed) {
7579                            if (!mSharedLibraries.containsKey(name)) {
7580                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7581                            } else if (!name.equals(pkg.packageName)) {
7582                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7583                                        + name + " already exists; skipping");
7584                            }
7585                        } else {
7586                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7587                                    + name + " that is not declared on system image; skipping");
7588                        }
7589                    }
7590                    if ((scanFlags & SCAN_BOOTING) == 0) {
7591                        // If we are not booting, we need to update any applications
7592                        // that are clients of our shared library.  If we are booting,
7593                        // this will all be done once the scan is complete.
7594                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7595                    }
7596                }
7597            }
7598        }
7599
7600        // Request the ActivityManager to kill the process(only for existing packages)
7601        // so that we do not end up in a confused state while the user is still using the older
7602        // version of the application while the new one gets installed.
7603        if ((scanFlags & SCAN_REPLACING) != 0) {
7604            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7605
7606            killApplication(pkg.applicationInfo.packageName,
7607                        pkg.applicationInfo.uid, "replace pkg");
7608
7609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7610        }
7611
7612        // Also need to kill any apps that are dependent on the library.
7613        if (clientLibPkgs != null) {
7614            for (int i=0; i<clientLibPkgs.size(); i++) {
7615                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7616                killApplication(clientPkg.applicationInfo.packageName,
7617                        clientPkg.applicationInfo.uid, "update lib");
7618            }
7619        }
7620
7621        // Make sure we're not adding any bogus keyset info
7622        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7623        ksms.assertScannedPackageValid(pkg);
7624
7625        // writer
7626        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7627
7628        boolean createIdmapFailed = false;
7629        synchronized (mPackages) {
7630            // We don't expect installation to fail beyond this point
7631
7632            // Add the new setting to mSettings
7633            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7634            // Add the new setting to mPackages
7635            mPackages.put(pkg.applicationInfo.packageName, pkg);
7636            // Make sure we don't accidentally delete its data.
7637            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7638            while (iter.hasNext()) {
7639                PackageCleanItem item = iter.next();
7640                if (pkgName.equals(item.packageName)) {
7641                    iter.remove();
7642                }
7643            }
7644
7645            // Take care of first install / last update times.
7646            if (currentTime != 0) {
7647                if (pkgSetting.firstInstallTime == 0) {
7648                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7649                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7650                    pkgSetting.lastUpdateTime = currentTime;
7651                }
7652            } else if (pkgSetting.firstInstallTime == 0) {
7653                // We need *something*.  Take time time stamp of the file.
7654                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7655            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7656                if (scanFileTime != pkgSetting.timeStamp) {
7657                    // A package on the system image has changed; consider this
7658                    // to be an update.
7659                    pkgSetting.lastUpdateTime = scanFileTime;
7660                }
7661            }
7662
7663            // Add the package's KeySets to the global KeySetManagerService
7664            ksms.addScannedPackageLPw(pkg);
7665
7666            int N = pkg.providers.size();
7667            StringBuilder r = null;
7668            int i;
7669            for (i=0; i<N; i++) {
7670                PackageParser.Provider p = pkg.providers.get(i);
7671                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7672                        p.info.processName, pkg.applicationInfo.uid);
7673                mProviders.addProvider(p);
7674                p.syncable = p.info.isSyncable;
7675                if (p.info.authority != null) {
7676                    String names[] = p.info.authority.split(";");
7677                    p.info.authority = null;
7678                    for (int j = 0; j < names.length; j++) {
7679                        if (j == 1 && p.syncable) {
7680                            // We only want the first authority for a provider to possibly be
7681                            // syncable, so if we already added this provider using a different
7682                            // authority clear the syncable flag. We copy the provider before
7683                            // changing it because the mProviders object contains a reference
7684                            // to a provider that we don't want to change.
7685                            // Only do this for the second authority since the resulting provider
7686                            // object can be the same for all future authorities for this provider.
7687                            p = new PackageParser.Provider(p);
7688                            p.syncable = false;
7689                        }
7690                        if (!mProvidersByAuthority.containsKey(names[j])) {
7691                            mProvidersByAuthority.put(names[j], p);
7692                            if (p.info.authority == null) {
7693                                p.info.authority = names[j];
7694                            } else {
7695                                p.info.authority = p.info.authority + ";" + names[j];
7696                            }
7697                            if (DEBUG_PACKAGE_SCANNING) {
7698                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7699                                    Log.d(TAG, "Registered content provider: " + names[j]
7700                                            + ", className = " + p.info.name + ", isSyncable = "
7701                                            + p.info.isSyncable);
7702                            }
7703                        } else {
7704                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7705                            Slog.w(TAG, "Skipping provider name " + names[j] +
7706                                    " (in package " + pkg.applicationInfo.packageName +
7707                                    "): name already used by "
7708                                    + ((other != null && other.getComponentName() != null)
7709                                            ? other.getComponentName().getPackageName() : "?"));
7710                        }
7711                    }
7712                }
7713                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7714                    if (r == null) {
7715                        r = new StringBuilder(256);
7716                    } else {
7717                        r.append(' ');
7718                    }
7719                    r.append(p.info.name);
7720                }
7721            }
7722            if (r != null) {
7723                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7724            }
7725
7726            N = pkg.services.size();
7727            r = null;
7728            for (i=0; i<N; i++) {
7729                PackageParser.Service s = pkg.services.get(i);
7730                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7731                        s.info.processName, pkg.applicationInfo.uid);
7732                mServices.addService(s);
7733                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7734                    if (r == null) {
7735                        r = new StringBuilder(256);
7736                    } else {
7737                        r.append(' ');
7738                    }
7739                    r.append(s.info.name);
7740                }
7741            }
7742            if (r != null) {
7743                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7744            }
7745
7746            N = pkg.receivers.size();
7747            r = null;
7748            for (i=0; i<N; i++) {
7749                PackageParser.Activity a = pkg.receivers.get(i);
7750                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7751                        a.info.processName, pkg.applicationInfo.uid);
7752                mReceivers.addActivity(a, "receiver");
7753                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7754                    if (r == null) {
7755                        r = new StringBuilder(256);
7756                    } else {
7757                        r.append(' ');
7758                    }
7759                    r.append(a.info.name);
7760                }
7761            }
7762            if (r != null) {
7763                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7764            }
7765
7766            N = pkg.activities.size();
7767            r = null;
7768            for (i=0; i<N; i++) {
7769                PackageParser.Activity a = pkg.activities.get(i);
7770                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7771                        a.info.processName, pkg.applicationInfo.uid);
7772                mActivities.addActivity(a, "activity");
7773                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7774                    if (r == null) {
7775                        r = new StringBuilder(256);
7776                    } else {
7777                        r.append(' ');
7778                    }
7779                    r.append(a.info.name);
7780                }
7781            }
7782            if (r != null) {
7783                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7784            }
7785
7786            N = pkg.permissionGroups.size();
7787            r = null;
7788            for (i=0; i<N; i++) {
7789                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7790                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7791                if (cur == null) {
7792                    mPermissionGroups.put(pg.info.name, pg);
7793                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7794                        if (r == null) {
7795                            r = new StringBuilder(256);
7796                        } else {
7797                            r.append(' ');
7798                        }
7799                        r.append(pg.info.name);
7800                    }
7801                } else {
7802                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7803                            + pg.info.packageName + " ignored: original from "
7804                            + cur.info.packageName);
7805                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7806                        if (r == null) {
7807                            r = new StringBuilder(256);
7808                        } else {
7809                            r.append(' ');
7810                        }
7811                        r.append("DUP:");
7812                        r.append(pg.info.name);
7813                    }
7814                }
7815            }
7816            if (r != null) {
7817                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7818            }
7819
7820            N = pkg.permissions.size();
7821            r = null;
7822            for (i=0; i<N; i++) {
7823                PackageParser.Permission p = pkg.permissions.get(i);
7824
7825                // Assume by default that we did not install this permission into the system.
7826                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7827
7828                // Now that permission groups have a special meaning, we ignore permission
7829                // groups for legacy apps to prevent unexpected behavior. In particular,
7830                // permissions for one app being granted to someone just becuase they happen
7831                // to be in a group defined by another app (before this had no implications).
7832                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7833                    p.group = mPermissionGroups.get(p.info.group);
7834                    // Warn for a permission in an unknown group.
7835                    if (p.info.group != null && p.group == null) {
7836                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7837                                + p.info.packageName + " in an unknown group " + p.info.group);
7838                    }
7839                }
7840
7841                ArrayMap<String, BasePermission> permissionMap =
7842                        p.tree ? mSettings.mPermissionTrees
7843                                : mSettings.mPermissions;
7844                BasePermission bp = permissionMap.get(p.info.name);
7845
7846                // Allow system apps to redefine non-system permissions
7847                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7848                    final boolean currentOwnerIsSystem = (bp.perm != null
7849                            && isSystemApp(bp.perm.owner));
7850                    if (isSystemApp(p.owner)) {
7851                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7852                            // It's a built-in permission and no owner, take ownership now
7853                            bp.packageSetting = pkgSetting;
7854                            bp.perm = p;
7855                            bp.uid = pkg.applicationInfo.uid;
7856                            bp.sourcePackage = p.info.packageName;
7857                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7858                        } else if (!currentOwnerIsSystem) {
7859                            String msg = "New decl " + p.owner + " of permission  "
7860                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7861                            reportSettingsProblem(Log.WARN, msg);
7862                            bp = null;
7863                        }
7864                    }
7865                }
7866
7867                if (bp == null) {
7868                    bp = new BasePermission(p.info.name, p.info.packageName,
7869                            BasePermission.TYPE_NORMAL);
7870                    permissionMap.put(p.info.name, bp);
7871                }
7872
7873                if (bp.perm == null) {
7874                    if (bp.sourcePackage == null
7875                            || bp.sourcePackage.equals(p.info.packageName)) {
7876                        BasePermission tree = findPermissionTreeLP(p.info.name);
7877                        if (tree == null
7878                                || tree.sourcePackage.equals(p.info.packageName)) {
7879                            bp.packageSetting = pkgSetting;
7880                            bp.perm = p;
7881                            bp.uid = pkg.applicationInfo.uid;
7882                            bp.sourcePackage = p.info.packageName;
7883                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7884                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7885                                if (r == null) {
7886                                    r = new StringBuilder(256);
7887                                } else {
7888                                    r.append(' ');
7889                                }
7890                                r.append(p.info.name);
7891                            }
7892                        } else {
7893                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7894                                    + p.info.packageName + " ignored: base tree "
7895                                    + tree.name + " is from package "
7896                                    + tree.sourcePackage);
7897                        }
7898                    } else {
7899                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7900                                + p.info.packageName + " ignored: original from "
7901                                + bp.sourcePackage);
7902                    }
7903                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7904                    if (r == null) {
7905                        r = new StringBuilder(256);
7906                    } else {
7907                        r.append(' ');
7908                    }
7909                    r.append("DUP:");
7910                    r.append(p.info.name);
7911                }
7912                if (bp.perm == p) {
7913                    bp.protectionLevel = p.info.protectionLevel;
7914                }
7915            }
7916
7917            if (r != null) {
7918                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7919            }
7920
7921            N = pkg.instrumentation.size();
7922            r = null;
7923            for (i=0; i<N; i++) {
7924                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7925                a.info.packageName = pkg.applicationInfo.packageName;
7926                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7927                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7928                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7929                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7930                a.info.dataDir = pkg.applicationInfo.dataDir;
7931                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7932                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7933
7934                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7935                // need other information about the application, like the ABI and what not ?
7936                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7937                mInstrumentation.put(a.getComponentName(), a);
7938                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7939                    if (r == null) {
7940                        r = new StringBuilder(256);
7941                    } else {
7942                        r.append(' ');
7943                    }
7944                    r.append(a.info.name);
7945                }
7946            }
7947            if (r != null) {
7948                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7949            }
7950
7951            if (pkg.protectedBroadcasts != null) {
7952                N = pkg.protectedBroadcasts.size();
7953                for (i=0; i<N; i++) {
7954                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7955                }
7956            }
7957
7958            pkgSetting.setTimeStamp(scanFileTime);
7959
7960            // Create idmap files for pairs of (packages, overlay packages).
7961            // Note: "android", ie framework-res.apk, is handled by native layers.
7962            if (pkg.mOverlayTarget != null) {
7963                // This is an overlay package.
7964                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7965                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7966                        mOverlays.put(pkg.mOverlayTarget,
7967                                new ArrayMap<String, PackageParser.Package>());
7968                    }
7969                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7970                    map.put(pkg.packageName, pkg);
7971                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7972                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7973                        createIdmapFailed = true;
7974                    }
7975                }
7976            } else if (mOverlays.containsKey(pkg.packageName) &&
7977                    !pkg.packageName.equals("android")) {
7978                // This is a regular package, with one or more known overlay packages.
7979                createIdmapsForPackageLI(pkg);
7980            }
7981        }
7982
7983        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7984
7985        if (createIdmapFailed) {
7986            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7987                    "scanPackageLI failed to createIdmap");
7988        }
7989        return pkg;
7990    }
7991
7992    /**
7993     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7994     * is derived purely on the basis of the contents of {@code scanFile} and
7995     * {@code cpuAbiOverride}.
7996     *
7997     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7998     */
7999    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8000                                 String cpuAbiOverride, boolean extractLibs)
8001            throws PackageManagerException {
8002        // TODO: We can probably be smarter about this stuff. For installed apps,
8003        // we can calculate this information at install time once and for all. For
8004        // system apps, we can probably assume that this information doesn't change
8005        // after the first boot scan. As things stand, we do lots of unnecessary work.
8006
8007        // Give ourselves some initial paths; we'll come back for another
8008        // pass once we've determined ABI below.
8009        setNativeLibraryPaths(pkg);
8010
8011        // We would never need to extract libs for forward-locked and external packages,
8012        // since the container service will do it for us. We shouldn't attempt to
8013        // extract libs from system app when it was not updated.
8014        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8015                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8016            extractLibs = false;
8017        }
8018
8019        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8020        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8021
8022        NativeLibraryHelper.Handle handle = null;
8023        try {
8024            handle = NativeLibraryHelper.Handle.create(pkg);
8025            // TODO(multiArch): This can be null for apps that didn't go through the
8026            // usual installation process. We can calculate it again, like we
8027            // do during install time.
8028            //
8029            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8030            // unnecessary.
8031            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8032
8033            // Null out the abis so that they can be recalculated.
8034            pkg.applicationInfo.primaryCpuAbi = null;
8035            pkg.applicationInfo.secondaryCpuAbi = null;
8036            if (isMultiArch(pkg.applicationInfo)) {
8037                // Warn if we've set an abiOverride for multi-lib packages..
8038                // By definition, we need to copy both 32 and 64 bit libraries for
8039                // such packages.
8040                if (pkg.cpuAbiOverride != null
8041                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8042                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8043                }
8044
8045                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8046                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8047                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8048                    if (extractLibs) {
8049                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8050                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8051                                useIsaSpecificSubdirs);
8052                    } else {
8053                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8054                    }
8055                }
8056
8057                maybeThrowExceptionForMultiArchCopy(
8058                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8059
8060                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8061                    if (extractLibs) {
8062                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8063                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8064                                useIsaSpecificSubdirs);
8065                    } else {
8066                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8067                    }
8068                }
8069
8070                maybeThrowExceptionForMultiArchCopy(
8071                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8072
8073                if (abi64 >= 0) {
8074                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8075                }
8076
8077                if (abi32 >= 0) {
8078                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8079                    if (abi64 >= 0) {
8080                        pkg.applicationInfo.secondaryCpuAbi = abi;
8081                    } else {
8082                        pkg.applicationInfo.primaryCpuAbi = abi;
8083                    }
8084                }
8085            } else {
8086                String[] abiList = (cpuAbiOverride != null) ?
8087                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8088
8089                // Enable gross and lame hacks for apps that are built with old
8090                // SDK tools. We must scan their APKs for renderscript bitcode and
8091                // not launch them if it's present. Don't bother checking on devices
8092                // that don't have 64 bit support.
8093                boolean needsRenderScriptOverride = false;
8094                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8095                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8096                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8097                    needsRenderScriptOverride = true;
8098                }
8099
8100                final int copyRet;
8101                if (extractLibs) {
8102                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8103                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8104                } else {
8105                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8106                }
8107
8108                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8109                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8110                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8111                }
8112
8113                if (copyRet >= 0) {
8114                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8115                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8116                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8117                } else if (needsRenderScriptOverride) {
8118                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8119                }
8120            }
8121        } catch (IOException ioe) {
8122            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8123        } finally {
8124            IoUtils.closeQuietly(handle);
8125        }
8126
8127        // Now that we've calculated the ABIs and determined if it's an internal app,
8128        // we will go ahead and populate the nativeLibraryPath.
8129        setNativeLibraryPaths(pkg);
8130    }
8131
8132    /**
8133     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8134     * i.e, so that all packages can be run inside a single process if required.
8135     *
8136     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8137     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8138     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8139     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8140     * updating a package that belongs to a shared user.
8141     *
8142     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8143     * adds unnecessary complexity.
8144     */
8145    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8146            PackageParser.Package scannedPackage, boolean bootComplete) {
8147        String requiredInstructionSet = null;
8148        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8149            requiredInstructionSet = VMRuntime.getInstructionSet(
8150                     scannedPackage.applicationInfo.primaryCpuAbi);
8151        }
8152
8153        PackageSetting requirer = null;
8154        for (PackageSetting ps : packagesForUser) {
8155            // If packagesForUser contains scannedPackage, we skip it. This will happen
8156            // when scannedPackage is an update of an existing package. Without this check,
8157            // we will never be able to change the ABI of any package belonging to a shared
8158            // user, even if it's compatible with other packages.
8159            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8160                if (ps.primaryCpuAbiString == null) {
8161                    continue;
8162                }
8163
8164                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8165                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8166                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8167                    // this but there's not much we can do.
8168                    String errorMessage = "Instruction set mismatch, "
8169                            + ((requirer == null) ? "[caller]" : requirer)
8170                            + " requires " + requiredInstructionSet + " whereas " + ps
8171                            + " requires " + instructionSet;
8172                    Slog.w(TAG, errorMessage);
8173                }
8174
8175                if (requiredInstructionSet == null) {
8176                    requiredInstructionSet = instructionSet;
8177                    requirer = ps;
8178                }
8179            }
8180        }
8181
8182        if (requiredInstructionSet != null) {
8183            String adjustedAbi;
8184            if (requirer != null) {
8185                // requirer != null implies that either scannedPackage was null or that scannedPackage
8186                // did not require an ABI, in which case we have to adjust scannedPackage to match
8187                // the ABI of the set (which is the same as requirer's ABI)
8188                adjustedAbi = requirer.primaryCpuAbiString;
8189                if (scannedPackage != null) {
8190                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8191                }
8192            } else {
8193                // requirer == null implies that we're updating all ABIs in the set to
8194                // match scannedPackage.
8195                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8196            }
8197
8198            for (PackageSetting ps : packagesForUser) {
8199                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8200                    if (ps.primaryCpuAbiString != null) {
8201                        continue;
8202                    }
8203
8204                    ps.primaryCpuAbiString = adjustedAbi;
8205                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8206                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8207                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8208                        try {
8209                            mInstaller.rmdex(ps.codePathString,
8210                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8211                        } catch (InstallerException ignored) {
8212                        }
8213                    }
8214                }
8215            }
8216        }
8217    }
8218
8219    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8220        synchronized (mPackages) {
8221            mResolverReplaced = true;
8222            // Set up information for custom user intent resolution activity.
8223            mResolveActivity.applicationInfo = pkg.applicationInfo;
8224            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8225            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8226            mResolveActivity.processName = pkg.applicationInfo.packageName;
8227            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8228            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8229                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8230            mResolveActivity.theme = 0;
8231            mResolveActivity.exported = true;
8232            mResolveActivity.enabled = true;
8233            mResolveInfo.activityInfo = mResolveActivity;
8234            mResolveInfo.priority = 0;
8235            mResolveInfo.preferredOrder = 0;
8236            mResolveInfo.match = 0;
8237            mResolveComponentName = mCustomResolverComponentName;
8238            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8239                    mResolveComponentName);
8240        }
8241    }
8242
8243    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8244        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8245
8246        // Set up information for ephemeral installer activity
8247        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8248        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8249        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8250        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8251        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8252        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8253                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8254        mEphemeralInstallerActivity.theme = 0;
8255        mEphemeralInstallerActivity.exported = true;
8256        mEphemeralInstallerActivity.enabled = true;
8257        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8258        mEphemeralInstallerInfo.priority = 0;
8259        mEphemeralInstallerInfo.preferredOrder = 0;
8260        mEphemeralInstallerInfo.match = 0;
8261
8262        if (DEBUG_EPHEMERAL) {
8263            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8264        }
8265    }
8266
8267    private static String calculateBundledApkRoot(final String codePathString) {
8268        final File codePath = new File(codePathString);
8269        final File codeRoot;
8270        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8271            codeRoot = Environment.getRootDirectory();
8272        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8273            codeRoot = Environment.getOemDirectory();
8274        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8275            codeRoot = Environment.getVendorDirectory();
8276        } else {
8277            // Unrecognized code path; take its top real segment as the apk root:
8278            // e.g. /something/app/blah.apk => /something
8279            try {
8280                File f = codePath.getCanonicalFile();
8281                File parent = f.getParentFile();    // non-null because codePath is a file
8282                File tmp;
8283                while ((tmp = parent.getParentFile()) != null) {
8284                    f = parent;
8285                    parent = tmp;
8286                }
8287                codeRoot = f;
8288                Slog.w(TAG, "Unrecognized code path "
8289                        + codePath + " - using " + codeRoot);
8290            } catch (IOException e) {
8291                // Can't canonicalize the code path -- shenanigans?
8292                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8293                return Environment.getRootDirectory().getPath();
8294            }
8295        }
8296        return codeRoot.getPath();
8297    }
8298
8299    /**
8300     * Derive and set the location of native libraries for the given package,
8301     * which varies depending on where and how the package was installed.
8302     */
8303    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8304        final ApplicationInfo info = pkg.applicationInfo;
8305        final String codePath = pkg.codePath;
8306        final File codeFile = new File(codePath);
8307        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8308        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8309
8310        info.nativeLibraryRootDir = null;
8311        info.nativeLibraryRootRequiresIsa = false;
8312        info.nativeLibraryDir = null;
8313        info.secondaryNativeLibraryDir = null;
8314
8315        if (isApkFile(codeFile)) {
8316            // Monolithic install
8317            if (bundledApp) {
8318                // If "/system/lib64/apkname" exists, assume that is the per-package
8319                // native library directory to use; otherwise use "/system/lib/apkname".
8320                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8321                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8322                        getPrimaryInstructionSet(info));
8323
8324                // This is a bundled system app so choose the path based on the ABI.
8325                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8326                // is just the default path.
8327                final String apkName = deriveCodePathName(codePath);
8328                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8329                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8330                        apkName).getAbsolutePath();
8331
8332                if (info.secondaryCpuAbi != null) {
8333                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8334                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8335                            secondaryLibDir, apkName).getAbsolutePath();
8336                }
8337            } else if (asecApp) {
8338                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8339                        .getAbsolutePath();
8340            } else {
8341                final String apkName = deriveCodePathName(codePath);
8342                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8343                        .getAbsolutePath();
8344            }
8345
8346            info.nativeLibraryRootRequiresIsa = false;
8347            info.nativeLibraryDir = info.nativeLibraryRootDir;
8348        } else {
8349            // Cluster install
8350            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8351            info.nativeLibraryRootRequiresIsa = true;
8352
8353            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8354                    getPrimaryInstructionSet(info)).getAbsolutePath();
8355
8356            if (info.secondaryCpuAbi != null) {
8357                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8358                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8359            }
8360        }
8361    }
8362
8363    /**
8364     * Calculate the abis and roots for a bundled app. These can uniquely
8365     * be determined from the contents of the system partition, i.e whether
8366     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8367     * of this information, and instead assume that the system was built
8368     * sensibly.
8369     */
8370    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8371                                           PackageSetting pkgSetting) {
8372        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8373
8374        // If "/system/lib64/apkname" exists, assume that is the per-package
8375        // native library directory to use; otherwise use "/system/lib/apkname".
8376        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8377        setBundledAppAbi(pkg, apkRoot, apkName);
8378        // pkgSetting might be null during rescan following uninstall of updates
8379        // to a bundled app, so accommodate that possibility.  The settings in
8380        // that case will be established later from the parsed package.
8381        //
8382        // If the settings aren't null, sync them up with what we've just derived.
8383        // note that apkRoot isn't stored in the package settings.
8384        if (pkgSetting != null) {
8385            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8386            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8387        }
8388    }
8389
8390    /**
8391     * Deduces the ABI of a bundled app and sets the relevant fields on the
8392     * parsed pkg object.
8393     *
8394     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8395     *        under which system libraries are installed.
8396     * @param apkName the name of the installed package.
8397     */
8398    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8399        final File codeFile = new File(pkg.codePath);
8400
8401        final boolean has64BitLibs;
8402        final boolean has32BitLibs;
8403        if (isApkFile(codeFile)) {
8404            // Monolithic install
8405            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8406            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8407        } else {
8408            // Cluster install
8409            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8410            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8411                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8412                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8413                has64BitLibs = (new File(rootDir, isa)).exists();
8414            } else {
8415                has64BitLibs = false;
8416            }
8417            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8418                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8419                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8420                has32BitLibs = (new File(rootDir, isa)).exists();
8421            } else {
8422                has32BitLibs = false;
8423            }
8424        }
8425
8426        if (has64BitLibs && !has32BitLibs) {
8427            // The package has 64 bit libs, but not 32 bit libs. Its primary
8428            // ABI should be 64 bit. We can safely assume here that the bundled
8429            // native libraries correspond to the most preferred ABI in the list.
8430
8431            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8432            pkg.applicationInfo.secondaryCpuAbi = null;
8433        } else if (has32BitLibs && !has64BitLibs) {
8434            // The package has 32 bit libs but not 64 bit libs. Its primary
8435            // ABI should be 32 bit.
8436
8437            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8438            pkg.applicationInfo.secondaryCpuAbi = null;
8439        } else if (has32BitLibs && has64BitLibs) {
8440            // The application has both 64 and 32 bit bundled libraries. We check
8441            // here that the app declares multiArch support, and warn if it doesn't.
8442            //
8443            // We will be lenient here and record both ABIs. The primary will be the
8444            // ABI that's higher on the list, i.e, a device that's configured to prefer
8445            // 64 bit apps will see a 64 bit primary ABI,
8446
8447            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8448                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8449            }
8450
8451            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8452                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8453                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8454            } else {
8455                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8456                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8457            }
8458        } else {
8459            pkg.applicationInfo.primaryCpuAbi = null;
8460            pkg.applicationInfo.secondaryCpuAbi = null;
8461        }
8462    }
8463
8464    private void killApplication(String pkgName, int appId, String reason) {
8465        // Request the ActivityManager to kill the process(only for existing packages)
8466        // so that we do not end up in a confused state while the user is still using the older
8467        // version of the application while the new one gets installed.
8468        IActivityManager am = ActivityManagerNative.getDefault();
8469        if (am != null) {
8470            try {
8471                am.killApplicationWithAppId(pkgName, appId, reason);
8472            } catch (RemoteException e) {
8473            }
8474        }
8475    }
8476
8477    void removePackageLI(PackageSetting ps, boolean chatty) {
8478        if (DEBUG_INSTALL) {
8479            if (chatty)
8480                Log.d(TAG, "Removing package " + ps.name);
8481        }
8482
8483        // writer
8484        synchronized (mPackages) {
8485            mPackages.remove(ps.name);
8486            final PackageParser.Package pkg = ps.pkg;
8487            if (pkg != null) {
8488                cleanPackageDataStructuresLILPw(pkg, chatty);
8489            }
8490        }
8491    }
8492
8493    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8494        if (DEBUG_INSTALL) {
8495            if (chatty)
8496                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8497        }
8498
8499        // writer
8500        synchronized (mPackages) {
8501            mPackages.remove(pkg.applicationInfo.packageName);
8502            cleanPackageDataStructuresLILPw(pkg, chatty);
8503        }
8504    }
8505
8506    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8507        int N = pkg.providers.size();
8508        StringBuilder r = null;
8509        int i;
8510        for (i=0; i<N; i++) {
8511            PackageParser.Provider p = pkg.providers.get(i);
8512            mProviders.removeProvider(p);
8513            if (p.info.authority == null) {
8514
8515                /* There was another ContentProvider with this authority when
8516                 * this app was installed so this authority is null,
8517                 * Ignore it as we don't have to unregister the provider.
8518                 */
8519                continue;
8520            }
8521            String names[] = p.info.authority.split(";");
8522            for (int j = 0; j < names.length; j++) {
8523                if (mProvidersByAuthority.get(names[j]) == p) {
8524                    mProvidersByAuthority.remove(names[j]);
8525                    if (DEBUG_REMOVE) {
8526                        if (chatty)
8527                            Log.d(TAG, "Unregistered content provider: " + names[j]
8528                                    + ", className = " + p.info.name + ", isSyncable = "
8529                                    + p.info.isSyncable);
8530                    }
8531                }
8532            }
8533            if (DEBUG_REMOVE && chatty) {
8534                if (r == null) {
8535                    r = new StringBuilder(256);
8536                } else {
8537                    r.append(' ');
8538                }
8539                r.append(p.info.name);
8540            }
8541        }
8542        if (r != null) {
8543            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8544        }
8545
8546        N = pkg.services.size();
8547        r = null;
8548        for (i=0; i<N; i++) {
8549            PackageParser.Service s = pkg.services.get(i);
8550            mServices.removeService(s);
8551            if (chatty) {
8552                if (r == null) {
8553                    r = new StringBuilder(256);
8554                } else {
8555                    r.append(' ');
8556                }
8557                r.append(s.info.name);
8558            }
8559        }
8560        if (r != null) {
8561            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8562        }
8563
8564        N = pkg.receivers.size();
8565        r = null;
8566        for (i=0; i<N; i++) {
8567            PackageParser.Activity a = pkg.receivers.get(i);
8568            mReceivers.removeActivity(a, "receiver");
8569            if (DEBUG_REMOVE && chatty) {
8570                if (r == null) {
8571                    r = new StringBuilder(256);
8572                } else {
8573                    r.append(' ');
8574                }
8575                r.append(a.info.name);
8576            }
8577        }
8578        if (r != null) {
8579            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8580        }
8581
8582        N = pkg.activities.size();
8583        r = null;
8584        for (i=0; i<N; i++) {
8585            PackageParser.Activity a = pkg.activities.get(i);
8586            mActivities.removeActivity(a, "activity");
8587            if (DEBUG_REMOVE && chatty) {
8588                if (r == null) {
8589                    r = new StringBuilder(256);
8590                } else {
8591                    r.append(' ');
8592                }
8593                r.append(a.info.name);
8594            }
8595        }
8596        if (r != null) {
8597            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8598        }
8599
8600        N = pkg.permissions.size();
8601        r = null;
8602        for (i=0; i<N; i++) {
8603            PackageParser.Permission p = pkg.permissions.get(i);
8604            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8605            if (bp == null) {
8606                bp = mSettings.mPermissionTrees.get(p.info.name);
8607            }
8608            if (bp != null && bp.perm == p) {
8609                bp.perm = null;
8610                if (DEBUG_REMOVE && chatty) {
8611                    if (r == null) {
8612                        r = new StringBuilder(256);
8613                    } else {
8614                        r.append(' ');
8615                    }
8616                    r.append(p.info.name);
8617                }
8618            }
8619            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8620                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8621                if (appOpPkgs != null) {
8622                    appOpPkgs.remove(pkg.packageName);
8623                }
8624            }
8625        }
8626        if (r != null) {
8627            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8628        }
8629
8630        N = pkg.requestedPermissions.size();
8631        r = null;
8632        for (i=0; i<N; i++) {
8633            String perm = pkg.requestedPermissions.get(i);
8634            BasePermission bp = mSettings.mPermissions.get(perm);
8635            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8636                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8637                if (appOpPkgs != null) {
8638                    appOpPkgs.remove(pkg.packageName);
8639                    if (appOpPkgs.isEmpty()) {
8640                        mAppOpPermissionPackages.remove(perm);
8641                    }
8642                }
8643            }
8644        }
8645        if (r != null) {
8646            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8647        }
8648
8649        N = pkg.instrumentation.size();
8650        r = null;
8651        for (i=0; i<N; i++) {
8652            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8653            mInstrumentation.remove(a.getComponentName());
8654            if (DEBUG_REMOVE && chatty) {
8655                if (r == null) {
8656                    r = new StringBuilder(256);
8657                } else {
8658                    r.append(' ');
8659                }
8660                r.append(a.info.name);
8661            }
8662        }
8663        if (r != null) {
8664            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8665        }
8666
8667        r = null;
8668        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8669            // Only system apps can hold shared libraries.
8670            if (pkg.libraryNames != null) {
8671                for (i=0; i<pkg.libraryNames.size(); i++) {
8672                    String name = pkg.libraryNames.get(i);
8673                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8674                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8675                        mSharedLibraries.remove(name);
8676                        if (DEBUG_REMOVE && chatty) {
8677                            if (r == null) {
8678                                r = new StringBuilder(256);
8679                            } else {
8680                                r.append(' ');
8681                            }
8682                            r.append(name);
8683                        }
8684                    }
8685                }
8686            }
8687        }
8688        if (r != null) {
8689            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8690        }
8691    }
8692
8693    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8694        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8695            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8696                return true;
8697            }
8698        }
8699        return false;
8700    }
8701
8702    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8703    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8704    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8705
8706    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8707            int flags) {
8708        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8709        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8710    }
8711
8712    private void updatePermissionsLPw(String changingPkg,
8713            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8714        // Make sure there are no dangling permission trees.
8715        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8716        while (it.hasNext()) {
8717            final BasePermission bp = it.next();
8718            if (bp.packageSetting == null) {
8719                // We may not yet have parsed the package, so just see if
8720                // we still know about its settings.
8721                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8722            }
8723            if (bp.packageSetting == null) {
8724                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8725                        + " from package " + bp.sourcePackage);
8726                it.remove();
8727            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8728                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8729                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8730                            + " from package " + bp.sourcePackage);
8731                    flags |= UPDATE_PERMISSIONS_ALL;
8732                    it.remove();
8733                }
8734            }
8735        }
8736
8737        // Make sure all dynamic permissions have been assigned to a package,
8738        // and make sure there are no dangling permissions.
8739        it = mSettings.mPermissions.values().iterator();
8740        while (it.hasNext()) {
8741            final BasePermission bp = it.next();
8742            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8743                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8744                        + bp.name + " pkg=" + bp.sourcePackage
8745                        + " info=" + bp.pendingInfo);
8746                if (bp.packageSetting == null && bp.pendingInfo != null) {
8747                    final BasePermission tree = findPermissionTreeLP(bp.name);
8748                    if (tree != null && tree.perm != null) {
8749                        bp.packageSetting = tree.packageSetting;
8750                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8751                                new PermissionInfo(bp.pendingInfo));
8752                        bp.perm.info.packageName = tree.perm.info.packageName;
8753                        bp.perm.info.name = bp.name;
8754                        bp.uid = tree.uid;
8755                    }
8756                }
8757            }
8758            if (bp.packageSetting == null) {
8759                // We may not yet have parsed the package, so just see if
8760                // we still know about its settings.
8761                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8762            }
8763            if (bp.packageSetting == null) {
8764                Slog.w(TAG, "Removing dangling permission: " + bp.name
8765                        + " from package " + bp.sourcePackage);
8766                it.remove();
8767            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8768                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8769                    Slog.i(TAG, "Removing old permission: " + bp.name
8770                            + " from package " + bp.sourcePackage);
8771                    flags |= UPDATE_PERMISSIONS_ALL;
8772                    it.remove();
8773                }
8774            }
8775        }
8776
8777        // Now update the permissions for all packages, in particular
8778        // replace the granted permissions of the system packages.
8779        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8780            for (PackageParser.Package pkg : mPackages.values()) {
8781                if (pkg != pkgInfo) {
8782                    // Only replace for packages on requested volume
8783                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8784                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8785                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8786                    grantPermissionsLPw(pkg, replace, changingPkg);
8787                }
8788            }
8789        }
8790
8791        if (pkgInfo != null) {
8792            // Only replace for packages on requested volume
8793            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8794            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8795                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8796            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8797        }
8798    }
8799
8800    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8801            String packageOfInterest) {
8802        // IMPORTANT: There are two types of permissions: install and runtime.
8803        // Install time permissions are granted when the app is installed to
8804        // all device users and users added in the future. Runtime permissions
8805        // are granted at runtime explicitly to specific users. Normal and signature
8806        // protected permissions are install time permissions. Dangerous permissions
8807        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8808        // otherwise they are runtime permissions. This function does not manage
8809        // runtime permissions except for the case an app targeting Lollipop MR1
8810        // being upgraded to target a newer SDK, in which case dangerous permissions
8811        // are transformed from install time to runtime ones.
8812
8813        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8814        if (ps == null) {
8815            return;
8816        }
8817
8818        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8819
8820        PermissionsState permissionsState = ps.getPermissionsState();
8821        PermissionsState origPermissions = permissionsState;
8822
8823        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8824
8825        boolean runtimePermissionsRevoked = false;
8826        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8827
8828        boolean changedInstallPermission = false;
8829
8830        if (replace) {
8831            ps.installPermissionsFixed = false;
8832            if (!ps.isSharedUser()) {
8833                origPermissions = new PermissionsState(permissionsState);
8834                permissionsState.reset();
8835            } else {
8836                // We need to know only about runtime permission changes since the
8837                // calling code always writes the install permissions state but
8838                // the runtime ones are written only if changed. The only cases of
8839                // changed runtime permissions here are promotion of an install to
8840                // runtime and revocation of a runtime from a shared user.
8841                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8842                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8843                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8844                    runtimePermissionsRevoked = true;
8845                }
8846            }
8847        }
8848
8849        permissionsState.setGlobalGids(mGlobalGids);
8850
8851        final int N = pkg.requestedPermissions.size();
8852        for (int i=0; i<N; i++) {
8853            final String name = pkg.requestedPermissions.get(i);
8854            final BasePermission bp = mSettings.mPermissions.get(name);
8855
8856            if (DEBUG_INSTALL) {
8857                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8858            }
8859
8860            if (bp == null || bp.packageSetting == null) {
8861                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8862                    Slog.w(TAG, "Unknown permission " + name
8863                            + " in package " + pkg.packageName);
8864                }
8865                continue;
8866            }
8867
8868            final String perm = bp.name;
8869            boolean allowedSig = false;
8870            int grant = GRANT_DENIED;
8871
8872            // Keep track of app op permissions.
8873            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8874                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8875                if (pkgs == null) {
8876                    pkgs = new ArraySet<>();
8877                    mAppOpPermissionPackages.put(bp.name, pkgs);
8878                }
8879                pkgs.add(pkg.packageName);
8880            }
8881
8882            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8883            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8884                    >= Build.VERSION_CODES.M;
8885            switch (level) {
8886                case PermissionInfo.PROTECTION_NORMAL: {
8887                    // For all apps normal permissions are install time ones.
8888                    grant = GRANT_INSTALL;
8889                } break;
8890
8891                case PermissionInfo.PROTECTION_DANGEROUS: {
8892                    // If a permission review is required for legacy apps we represent
8893                    // their permissions as always granted runtime ones since we need
8894                    // to keep the review required permission flag per user while an
8895                    // install permission's state is shared across all users.
8896                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8897                        // For legacy apps dangerous permissions are install time ones.
8898                        grant = GRANT_INSTALL;
8899                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8900                        // For legacy apps that became modern, install becomes runtime.
8901                        grant = GRANT_UPGRADE;
8902                    } else if (mPromoteSystemApps
8903                            && isSystemApp(ps)
8904                            && mExistingSystemPackages.contains(ps.name)) {
8905                        // For legacy system apps, install becomes runtime.
8906                        // We cannot check hasInstallPermission() for system apps since those
8907                        // permissions were granted implicitly and not persisted pre-M.
8908                        grant = GRANT_UPGRADE;
8909                    } else {
8910                        // For modern apps keep runtime permissions unchanged.
8911                        grant = GRANT_RUNTIME;
8912                    }
8913                } break;
8914
8915                case PermissionInfo.PROTECTION_SIGNATURE: {
8916                    // For all apps signature permissions are install time ones.
8917                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8918                    if (allowedSig) {
8919                        grant = GRANT_INSTALL;
8920                    }
8921                } break;
8922            }
8923
8924            if (DEBUG_INSTALL) {
8925                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8926            }
8927
8928            if (grant != GRANT_DENIED) {
8929                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8930                    // If this is an existing, non-system package, then
8931                    // we can't add any new permissions to it.
8932                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8933                        // Except...  if this is a permission that was added
8934                        // to the platform (note: need to only do this when
8935                        // updating the platform).
8936                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8937                            grant = GRANT_DENIED;
8938                        }
8939                    }
8940                }
8941
8942                switch (grant) {
8943                    case GRANT_INSTALL: {
8944                        // Revoke this as runtime permission to handle the case of
8945                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8946                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8947                            if (origPermissions.getRuntimePermissionState(
8948                                    bp.name, userId) != null) {
8949                                // Revoke the runtime permission and clear the flags.
8950                                origPermissions.revokeRuntimePermission(bp, userId);
8951                                origPermissions.updatePermissionFlags(bp, userId,
8952                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8953                                // If we revoked a permission permission, we have to write.
8954                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8955                                        changedRuntimePermissionUserIds, userId);
8956                            }
8957                        }
8958                        // Grant an install permission.
8959                        if (permissionsState.grantInstallPermission(bp) !=
8960                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8961                            changedInstallPermission = true;
8962                        }
8963                    } break;
8964
8965                    case GRANT_RUNTIME: {
8966                        // Grant previously granted runtime permissions.
8967                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8968                            PermissionState permissionState = origPermissions
8969                                    .getRuntimePermissionState(bp.name, userId);
8970                            int flags = permissionState != null
8971                                    ? permissionState.getFlags() : 0;
8972                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8973                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8974                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8975                                    // If we cannot put the permission as it was, we have to write.
8976                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8977                                            changedRuntimePermissionUserIds, userId);
8978                                }
8979                                // If the app supports runtime permissions no need for a review.
8980                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8981                                        && appSupportsRuntimePermissions
8982                                        && (flags & PackageManager
8983                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8984                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8985                                    // Since we changed the flags, we have to write.
8986                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8987                                            changedRuntimePermissionUserIds, userId);
8988                                }
8989                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8990                                    && !appSupportsRuntimePermissions) {
8991                                // For legacy apps that need a permission review, every new
8992                                // runtime permission is granted but it is pending a review.
8993                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8994                                    permissionsState.grantRuntimePermission(bp, userId);
8995                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8996                                    // We changed the permission and flags, hence have to write.
8997                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8998                                            changedRuntimePermissionUserIds, userId);
8999                                }
9000                            }
9001                            // Propagate the permission flags.
9002                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9003                        }
9004                    } break;
9005
9006                    case GRANT_UPGRADE: {
9007                        // Grant runtime permissions for a previously held install permission.
9008                        PermissionState permissionState = origPermissions
9009                                .getInstallPermissionState(bp.name);
9010                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9011
9012                        if (origPermissions.revokeInstallPermission(bp)
9013                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9014                            // We will be transferring the permission flags, so clear them.
9015                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9016                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9017                            changedInstallPermission = true;
9018                        }
9019
9020                        // If the permission is not to be promoted to runtime we ignore it and
9021                        // also its other flags as they are not applicable to install permissions.
9022                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9023                            for (int userId : currentUserIds) {
9024                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9025                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9026                                    // Transfer the permission flags.
9027                                    permissionsState.updatePermissionFlags(bp, userId,
9028                                            flags, flags);
9029                                    // If we granted the permission, we have to write.
9030                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9031                                            changedRuntimePermissionUserIds, userId);
9032                                }
9033                            }
9034                        }
9035                    } break;
9036
9037                    default: {
9038                        if (packageOfInterest == null
9039                                || packageOfInterest.equals(pkg.packageName)) {
9040                            Slog.w(TAG, "Not granting permission " + perm
9041                                    + " to package " + pkg.packageName
9042                                    + " because it was previously installed without");
9043                        }
9044                    } break;
9045                }
9046            } else {
9047                if (permissionsState.revokeInstallPermission(bp) !=
9048                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9049                    // Also drop the permission flags.
9050                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9051                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9052                    changedInstallPermission = true;
9053                    Slog.i(TAG, "Un-granting permission " + perm
9054                            + " from package " + pkg.packageName
9055                            + " (protectionLevel=" + bp.protectionLevel
9056                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9057                            + ")");
9058                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9059                    // Don't print warning for app op permissions, since it is fine for them
9060                    // not to be granted, there is a UI for the user to decide.
9061                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9062                        Slog.w(TAG, "Not granting permission " + perm
9063                                + " to package " + pkg.packageName
9064                                + " (protectionLevel=" + bp.protectionLevel
9065                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9066                                + ")");
9067                    }
9068                }
9069            }
9070        }
9071
9072        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9073                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9074            // This is the first that we have heard about this package, so the
9075            // permissions we have now selected are fixed until explicitly
9076            // changed.
9077            ps.installPermissionsFixed = true;
9078        }
9079
9080        // Persist the runtime permissions state for users with changes. If permissions
9081        // were revoked because no app in the shared user declares them we have to
9082        // write synchronously to avoid losing runtime permissions state.
9083        for (int userId : changedRuntimePermissionUserIds) {
9084            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9085        }
9086
9087        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9088    }
9089
9090    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9091        boolean allowed = false;
9092        final int NP = PackageParser.NEW_PERMISSIONS.length;
9093        for (int ip=0; ip<NP; ip++) {
9094            final PackageParser.NewPermissionInfo npi
9095                    = PackageParser.NEW_PERMISSIONS[ip];
9096            if (npi.name.equals(perm)
9097                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9098                allowed = true;
9099                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9100                        + pkg.packageName);
9101                break;
9102            }
9103        }
9104        return allowed;
9105    }
9106
9107    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9108            BasePermission bp, PermissionsState origPermissions) {
9109        boolean allowed;
9110        allowed = (compareSignatures(
9111                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9112                        == PackageManager.SIGNATURE_MATCH)
9113                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9114                        == PackageManager.SIGNATURE_MATCH);
9115        if (!allowed && (bp.protectionLevel
9116                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9117            if (isSystemApp(pkg)) {
9118                // For updated system applications, a system permission
9119                // is granted only if it had been defined by the original application.
9120                if (pkg.isUpdatedSystemApp()) {
9121                    final PackageSetting sysPs = mSettings
9122                            .getDisabledSystemPkgLPr(pkg.packageName);
9123                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9124                        // If the original was granted this permission, we take
9125                        // that grant decision as read and propagate it to the
9126                        // update.
9127                        if (sysPs.isPrivileged()) {
9128                            allowed = true;
9129                        }
9130                    } else {
9131                        // The system apk may have been updated with an older
9132                        // version of the one on the data partition, but which
9133                        // granted a new system permission that it didn't have
9134                        // before.  In this case we do want to allow the app to
9135                        // now get the new permission if the ancestral apk is
9136                        // privileged to get it.
9137                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9138                            for (int j=0;
9139                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9140                                if (perm.equals(
9141                                        sysPs.pkg.requestedPermissions.get(j))) {
9142                                    allowed = true;
9143                                    break;
9144                                }
9145                            }
9146                        }
9147                    }
9148                } else {
9149                    allowed = isPrivilegedApp(pkg);
9150                }
9151            }
9152        }
9153        if (!allowed) {
9154            if (!allowed && (bp.protectionLevel
9155                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9156                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9157                // If this was a previously normal/dangerous permission that got moved
9158                // to a system permission as part of the runtime permission redesign, then
9159                // we still want to blindly grant it to old apps.
9160                allowed = true;
9161            }
9162            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9163                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9164                // If this permission is to be granted to the system installer and
9165                // this app is an installer, then it gets the permission.
9166                allowed = true;
9167            }
9168            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9169                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9170                // If this permission is to be granted to the system verifier and
9171                // this app is a verifier, then it gets the permission.
9172                allowed = true;
9173            }
9174            if (!allowed && (bp.protectionLevel
9175                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9176                    && isSystemApp(pkg)) {
9177                // Any pre-installed system app is allowed to get this permission.
9178                allowed = true;
9179            }
9180            if (!allowed && (bp.protectionLevel
9181                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9182                // For development permissions, a development permission
9183                // is granted only if it was already granted.
9184                allowed = origPermissions.hasInstallPermission(perm);
9185            }
9186        }
9187        return allowed;
9188    }
9189
9190    final class ActivityIntentResolver
9191            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9192        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9193                boolean defaultOnly, int userId) {
9194            if (!sUserManager.exists(userId)) return null;
9195            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9196            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9197        }
9198
9199        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9200                int userId) {
9201            if (!sUserManager.exists(userId)) return null;
9202            mFlags = flags;
9203            return super.queryIntent(intent, resolvedType,
9204                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9205        }
9206
9207        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9208                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9209            if (!sUserManager.exists(userId)) return null;
9210            if (packageActivities == null) {
9211                return null;
9212            }
9213            mFlags = flags;
9214            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9215            final int N = packageActivities.size();
9216            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9217                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9218
9219            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9220            for (int i = 0; i < N; ++i) {
9221                intentFilters = packageActivities.get(i).intents;
9222                if (intentFilters != null && intentFilters.size() > 0) {
9223                    PackageParser.ActivityIntentInfo[] array =
9224                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9225                    intentFilters.toArray(array);
9226                    listCut.add(array);
9227                }
9228            }
9229            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9230        }
9231
9232        public final void addActivity(PackageParser.Activity a, String type) {
9233            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9234            mActivities.put(a.getComponentName(), a);
9235            if (DEBUG_SHOW_INFO)
9236                Log.v(
9237                TAG, "  " + type + " " +
9238                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9239            if (DEBUG_SHOW_INFO)
9240                Log.v(TAG, "    Class=" + a.info.name);
9241            final int NI = a.intents.size();
9242            for (int j=0; j<NI; j++) {
9243                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9244                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9245                    intent.setPriority(0);
9246                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9247                            + a.className + " with priority > 0, forcing to 0");
9248                }
9249                if (DEBUG_SHOW_INFO) {
9250                    Log.v(TAG, "    IntentFilter:");
9251                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9252                }
9253                if (!intent.debugCheck()) {
9254                    Log.w(TAG, "==> For Activity " + a.info.name);
9255                }
9256                addFilter(intent);
9257            }
9258        }
9259
9260        public final void removeActivity(PackageParser.Activity a, String type) {
9261            mActivities.remove(a.getComponentName());
9262            if (DEBUG_SHOW_INFO) {
9263                Log.v(TAG, "  " + type + " "
9264                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9265                                : a.info.name) + ":");
9266                Log.v(TAG, "    Class=" + a.info.name);
9267            }
9268            final int NI = a.intents.size();
9269            for (int j=0; j<NI; j++) {
9270                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9271                if (DEBUG_SHOW_INFO) {
9272                    Log.v(TAG, "    IntentFilter:");
9273                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9274                }
9275                removeFilter(intent);
9276            }
9277        }
9278
9279        @Override
9280        protected boolean allowFilterResult(
9281                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9282            ActivityInfo filterAi = filter.activity.info;
9283            for (int i=dest.size()-1; i>=0; i--) {
9284                ActivityInfo destAi = dest.get(i).activityInfo;
9285                if (destAi.name == filterAi.name
9286                        && destAi.packageName == filterAi.packageName) {
9287                    return false;
9288                }
9289            }
9290            return true;
9291        }
9292
9293        @Override
9294        protected ActivityIntentInfo[] newArray(int size) {
9295            return new ActivityIntentInfo[size];
9296        }
9297
9298        @Override
9299        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9300            if (!sUserManager.exists(userId)) return true;
9301            PackageParser.Package p = filter.activity.owner;
9302            if (p != null) {
9303                PackageSetting ps = (PackageSetting)p.mExtras;
9304                if (ps != null) {
9305                    // System apps are never considered stopped for purposes of
9306                    // filtering, because there may be no way for the user to
9307                    // actually re-launch them.
9308                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9309                            && ps.getStopped(userId);
9310                }
9311            }
9312            return false;
9313        }
9314
9315        @Override
9316        protected boolean isPackageForFilter(String packageName,
9317                PackageParser.ActivityIntentInfo info) {
9318            return packageName.equals(info.activity.owner.packageName);
9319        }
9320
9321        @Override
9322        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9323                int match, int userId) {
9324            if (!sUserManager.exists(userId)) return null;
9325            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9326                return null;
9327            }
9328            final PackageParser.Activity activity = info.activity;
9329            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9330            if (ps == null) {
9331                return null;
9332            }
9333            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9334                    ps.readUserState(userId), userId);
9335            if (ai == null) {
9336                return null;
9337            }
9338            final ResolveInfo res = new ResolveInfo();
9339            res.activityInfo = ai;
9340            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9341                res.filter = info;
9342            }
9343            if (info != null) {
9344                res.handleAllWebDataURI = info.handleAllWebDataURI();
9345            }
9346            res.priority = info.getPriority();
9347            res.preferredOrder = activity.owner.mPreferredOrder;
9348            //System.out.println("Result: " + res.activityInfo.className +
9349            //                   " = " + res.priority);
9350            res.match = match;
9351            res.isDefault = info.hasDefault;
9352            res.labelRes = info.labelRes;
9353            res.nonLocalizedLabel = info.nonLocalizedLabel;
9354            if (userNeedsBadging(userId)) {
9355                res.noResourceId = true;
9356            } else {
9357                res.icon = info.icon;
9358            }
9359            res.iconResourceId = info.icon;
9360            res.system = res.activityInfo.applicationInfo.isSystemApp();
9361            return res;
9362        }
9363
9364        @Override
9365        protected void sortResults(List<ResolveInfo> results) {
9366            Collections.sort(results, mResolvePrioritySorter);
9367        }
9368
9369        @Override
9370        protected void dumpFilter(PrintWriter out, String prefix,
9371                PackageParser.ActivityIntentInfo filter) {
9372            out.print(prefix); out.print(
9373                    Integer.toHexString(System.identityHashCode(filter.activity)));
9374                    out.print(' ');
9375                    filter.activity.printComponentShortName(out);
9376                    out.print(" filter ");
9377                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9378        }
9379
9380        @Override
9381        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9382            return filter.activity;
9383        }
9384
9385        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9386            PackageParser.Activity activity = (PackageParser.Activity)label;
9387            out.print(prefix); out.print(
9388                    Integer.toHexString(System.identityHashCode(activity)));
9389                    out.print(' ');
9390                    activity.printComponentShortName(out);
9391            if (count > 1) {
9392                out.print(" ("); out.print(count); out.print(" filters)");
9393            }
9394            out.println();
9395        }
9396
9397//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9398//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9399//            final List<ResolveInfo> retList = Lists.newArrayList();
9400//            while (i.hasNext()) {
9401//                final ResolveInfo resolveInfo = i.next();
9402//                if (isEnabledLP(resolveInfo.activityInfo)) {
9403//                    retList.add(resolveInfo);
9404//                }
9405//            }
9406//            return retList;
9407//        }
9408
9409        // Keys are String (activity class name), values are Activity.
9410        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9411                = new ArrayMap<ComponentName, PackageParser.Activity>();
9412        private int mFlags;
9413    }
9414
9415    private final class ServiceIntentResolver
9416            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9417        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9418                boolean defaultOnly, int userId) {
9419            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9420            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9421        }
9422
9423        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9424                int userId) {
9425            if (!sUserManager.exists(userId)) return null;
9426            mFlags = flags;
9427            return super.queryIntent(intent, resolvedType,
9428                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9429        }
9430
9431        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9432                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9433            if (!sUserManager.exists(userId)) return null;
9434            if (packageServices == null) {
9435                return null;
9436            }
9437            mFlags = flags;
9438            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9439            final int N = packageServices.size();
9440            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9441                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9442
9443            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9444            for (int i = 0; i < N; ++i) {
9445                intentFilters = packageServices.get(i).intents;
9446                if (intentFilters != null && intentFilters.size() > 0) {
9447                    PackageParser.ServiceIntentInfo[] array =
9448                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9449                    intentFilters.toArray(array);
9450                    listCut.add(array);
9451                }
9452            }
9453            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9454        }
9455
9456        public final void addService(PackageParser.Service s) {
9457            mServices.put(s.getComponentName(), s);
9458            if (DEBUG_SHOW_INFO) {
9459                Log.v(TAG, "  "
9460                        + (s.info.nonLocalizedLabel != null
9461                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9462                Log.v(TAG, "    Class=" + s.info.name);
9463            }
9464            final int NI = s.intents.size();
9465            int j;
9466            for (j=0; j<NI; j++) {
9467                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9468                if (DEBUG_SHOW_INFO) {
9469                    Log.v(TAG, "    IntentFilter:");
9470                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9471                }
9472                if (!intent.debugCheck()) {
9473                    Log.w(TAG, "==> For Service " + s.info.name);
9474                }
9475                addFilter(intent);
9476            }
9477        }
9478
9479        public final void removeService(PackageParser.Service s) {
9480            mServices.remove(s.getComponentName());
9481            if (DEBUG_SHOW_INFO) {
9482                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9483                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9484                Log.v(TAG, "    Class=" + s.info.name);
9485            }
9486            final int NI = s.intents.size();
9487            int j;
9488            for (j=0; j<NI; j++) {
9489                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9490                if (DEBUG_SHOW_INFO) {
9491                    Log.v(TAG, "    IntentFilter:");
9492                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9493                }
9494                removeFilter(intent);
9495            }
9496        }
9497
9498        @Override
9499        protected boolean allowFilterResult(
9500                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9501            ServiceInfo filterSi = filter.service.info;
9502            for (int i=dest.size()-1; i>=0; i--) {
9503                ServiceInfo destAi = dest.get(i).serviceInfo;
9504                if (destAi.name == filterSi.name
9505                        && destAi.packageName == filterSi.packageName) {
9506                    return false;
9507                }
9508            }
9509            return true;
9510        }
9511
9512        @Override
9513        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9514            return new PackageParser.ServiceIntentInfo[size];
9515        }
9516
9517        @Override
9518        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9519            if (!sUserManager.exists(userId)) return true;
9520            PackageParser.Package p = filter.service.owner;
9521            if (p != null) {
9522                PackageSetting ps = (PackageSetting)p.mExtras;
9523                if (ps != null) {
9524                    // System apps are never considered stopped for purposes of
9525                    // filtering, because there may be no way for the user to
9526                    // actually re-launch them.
9527                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9528                            && ps.getStopped(userId);
9529                }
9530            }
9531            return false;
9532        }
9533
9534        @Override
9535        protected boolean isPackageForFilter(String packageName,
9536                PackageParser.ServiceIntentInfo info) {
9537            return packageName.equals(info.service.owner.packageName);
9538        }
9539
9540        @Override
9541        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9542                int match, int userId) {
9543            if (!sUserManager.exists(userId)) return null;
9544            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9545            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9546                return null;
9547            }
9548            final PackageParser.Service service = info.service;
9549            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9550            if (ps == null) {
9551                return null;
9552            }
9553            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9554                    ps.readUserState(userId), userId);
9555            if (si == null) {
9556                return null;
9557            }
9558            final ResolveInfo res = new ResolveInfo();
9559            res.serviceInfo = si;
9560            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9561                res.filter = filter;
9562            }
9563            res.priority = info.getPriority();
9564            res.preferredOrder = service.owner.mPreferredOrder;
9565            res.match = match;
9566            res.isDefault = info.hasDefault;
9567            res.labelRes = info.labelRes;
9568            res.nonLocalizedLabel = info.nonLocalizedLabel;
9569            res.icon = info.icon;
9570            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9571            return res;
9572        }
9573
9574        @Override
9575        protected void sortResults(List<ResolveInfo> results) {
9576            Collections.sort(results, mResolvePrioritySorter);
9577        }
9578
9579        @Override
9580        protected void dumpFilter(PrintWriter out, String prefix,
9581                PackageParser.ServiceIntentInfo filter) {
9582            out.print(prefix); out.print(
9583                    Integer.toHexString(System.identityHashCode(filter.service)));
9584                    out.print(' ');
9585                    filter.service.printComponentShortName(out);
9586                    out.print(" filter ");
9587                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9588        }
9589
9590        @Override
9591        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9592            return filter.service;
9593        }
9594
9595        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9596            PackageParser.Service service = (PackageParser.Service)label;
9597            out.print(prefix); out.print(
9598                    Integer.toHexString(System.identityHashCode(service)));
9599                    out.print(' ');
9600                    service.printComponentShortName(out);
9601            if (count > 1) {
9602                out.print(" ("); out.print(count); out.print(" filters)");
9603            }
9604            out.println();
9605        }
9606
9607//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9608//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9609//            final List<ResolveInfo> retList = Lists.newArrayList();
9610//            while (i.hasNext()) {
9611//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9612//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9613//                    retList.add(resolveInfo);
9614//                }
9615//            }
9616//            return retList;
9617//        }
9618
9619        // Keys are String (activity class name), values are Activity.
9620        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9621                = new ArrayMap<ComponentName, PackageParser.Service>();
9622        private int mFlags;
9623    };
9624
9625    private final class ProviderIntentResolver
9626            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9627        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9628                boolean defaultOnly, int userId) {
9629            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9630            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9631        }
9632
9633        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9634                int userId) {
9635            if (!sUserManager.exists(userId))
9636                return null;
9637            mFlags = flags;
9638            return super.queryIntent(intent, resolvedType,
9639                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9640        }
9641
9642        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9643                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9644            if (!sUserManager.exists(userId))
9645                return null;
9646            if (packageProviders == null) {
9647                return null;
9648            }
9649            mFlags = flags;
9650            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9651            final int N = packageProviders.size();
9652            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9653                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9654
9655            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9656            for (int i = 0; i < N; ++i) {
9657                intentFilters = packageProviders.get(i).intents;
9658                if (intentFilters != null && intentFilters.size() > 0) {
9659                    PackageParser.ProviderIntentInfo[] array =
9660                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9661                    intentFilters.toArray(array);
9662                    listCut.add(array);
9663                }
9664            }
9665            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9666        }
9667
9668        public final void addProvider(PackageParser.Provider p) {
9669            if (mProviders.containsKey(p.getComponentName())) {
9670                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9671                return;
9672            }
9673
9674            mProviders.put(p.getComponentName(), p);
9675            if (DEBUG_SHOW_INFO) {
9676                Log.v(TAG, "  "
9677                        + (p.info.nonLocalizedLabel != null
9678                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9679                Log.v(TAG, "    Class=" + p.info.name);
9680            }
9681            final int NI = p.intents.size();
9682            int j;
9683            for (j = 0; j < NI; j++) {
9684                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9685                if (DEBUG_SHOW_INFO) {
9686                    Log.v(TAG, "    IntentFilter:");
9687                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9688                }
9689                if (!intent.debugCheck()) {
9690                    Log.w(TAG, "==> For Provider " + p.info.name);
9691                }
9692                addFilter(intent);
9693            }
9694        }
9695
9696        public final void removeProvider(PackageParser.Provider p) {
9697            mProviders.remove(p.getComponentName());
9698            if (DEBUG_SHOW_INFO) {
9699                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9700                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9701                Log.v(TAG, "    Class=" + p.info.name);
9702            }
9703            final int NI = p.intents.size();
9704            int j;
9705            for (j = 0; j < NI; j++) {
9706                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9707                if (DEBUG_SHOW_INFO) {
9708                    Log.v(TAG, "    IntentFilter:");
9709                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9710                }
9711                removeFilter(intent);
9712            }
9713        }
9714
9715        @Override
9716        protected boolean allowFilterResult(
9717                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9718            ProviderInfo filterPi = filter.provider.info;
9719            for (int i = dest.size() - 1; i >= 0; i--) {
9720                ProviderInfo destPi = dest.get(i).providerInfo;
9721                if (destPi.name == filterPi.name
9722                        && destPi.packageName == filterPi.packageName) {
9723                    return false;
9724                }
9725            }
9726            return true;
9727        }
9728
9729        @Override
9730        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9731            return new PackageParser.ProviderIntentInfo[size];
9732        }
9733
9734        @Override
9735        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9736            if (!sUserManager.exists(userId))
9737                return true;
9738            PackageParser.Package p = filter.provider.owner;
9739            if (p != null) {
9740                PackageSetting ps = (PackageSetting) p.mExtras;
9741                if (ps != null) {
9742                    // System apps are never considered stopped for purposes of
9743                    // filtering, because there may be no way for the user to
9744                    // actually re-launch them.
9745                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9746                            && ps.getStopped(userId);
9747                }
9748            }
9749            return false;
9750        }
9751
9752        @Override
9753        protected boolean isPackageForFilter(String packageName,
9754                PackageParser.ProviderIntentInfo info) {
9755            return packageName.equals(info.provider.owner.packageName);
9756        }
9757
9758        @Override
9759        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9760                int match, int userId) {
9761            if (!sUserManager.exists(userId))
9762                return null;
9763            final PackageParser.ProviderIntentInfo info = filter;
9764            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9765                return null;
9766            }
9767            final PackageParser.Provider provider = info.provider;
9768            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9769            if (ps == null) {
9770                return null;
9771            }
9772            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9773                    ps.readUserState(userId), userId);
9774            if (pi == null) {
9775                return null;
9776            }
9777            final ResolveInfo res = new ResolveInfo();
9778            res.providerInfo = pi;
9779            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9780                res.filter = filter;
9781            }
9782            res.priority = info.getPriority();
9783            res.preferredOrder = provider.owner.mPreferredOrder;
9784            res.match = match;
9785            res.isDefault = info.hasDefault;
9786            res.labelRes = info.labelRes;
9787            res.nonLocalizedLabel = info.nonLocalizedLabel;
9788            res.icon = info.icon;
9789            res.system = res.providerInfo.applicationInfo.isSystemApp();
9790            return res;
9791        }
9792
9793        @Override
9794        protected void sortResults(List<ResolveInfo> results) {
9795            Collections.sort(results, mResolvePrioritySorter);
9796        }
9797
9798        @Override
9799        protected void dumpFilter(PrintWriter out, String prefix,
9800                PackageParser.ProviderIntentInfo filter) {
9801            out.print(prefix);
9802            out.print(
9803                    Integer.toHexString(System.identityHashCode(filter.provider)));
9804            out.print(' ');
9805            filter.provider.printComponentShortName(out);
9806            out.print(" filter ");
9807            out.println(Integer.toHexString(System.identityHashCode(filter)));
9808        }
9809
9810        @Override
9811        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9812            return filter.provider;
9813        }
9814
9815        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9816            PackageParser.Provider provider = (PackageParser.Provider)label;
9817            out.print(prefix); out.print(
9818                    Integer.toHexString(System.identityHashCode(provider)));
9819                    out.print(' ');
9820                    provider.printComponentShortName(out);
9821            if (count > 1) {
9822                out.print(" ("); out.print(count); out.print(" filters)");
9823            }
9824            out.println();
9825        }
9826
9827        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9828                = new ArrayMap<ComponentName, PackageParser.Provider>();
9829        private int mFlags;
9830    }
9831
9832    private static final class EphemeralIntentResolver
9833            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9834        @Override
9835        protected EphemeralResolveIntentInfo[] newArray(int size) {
9836            return new EphemeralResolveIntentInfo[size];
9837        }
9838
9839        @Override
9840        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9841            return true;
9842        }
9843
9844        @Override
9845        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9846                int userId) {
9847            if (!sUserManager.exists(userId)) {
9848                return null;
9849            }
9850            return info.getEphemeralResolveInfo();
9851        }
9852    }
9853
9854    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9855            new Comparator<ResolveInfo>() {
9856        public int compare(ResolveInfo r1, ResolveInfo r2) {
9857            int v1 = r1.priority;
9858            int v2 = r2.priority;
9859            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9860            if (v1 != v2) {
9861                return (v1 > v2) ? -1 : 1;
9862            }
9863            v1 = r1.preferredOrder;
9864            v2 = r2.preferredOrder;
9865            if (v1 != v2) {
9866                return (v1 > v2) ? -1 : 1;
9867            }
9868            if (r1.isDefault != r2.isDefault) {
9869                return r1.isDefault ? -1 : 1;
9870            }
9871            v1 = r1.match;
9872            v2 = r2.match;
9873            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9874            if (v1 != v2) {
9875                return (v1 > v2) ? -1 : 1;
9876            }
9877            if (r1.system != r2.system) {
9878                return r1.system ? -1 : 1;
9879            }
9880            if (r1.activityInfo != null) {
9881                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9882            }
9883            if (r1.serviceInfo != null) {
9884                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9885            }
9886            if (r1.providerInfo != null) {
9887                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9888            }
9889            return 0;
9890        }
9891    };
9892
9893    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9894            new Comparator<ProviderInfo>() {
9895        public int compare(ProviderInfo p1, ProviderInfo p2) {
9896            final int v1 = p1.initOrder;
9897            final int v2 = p2.initOrder;
9898            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9899        }
9900    };
9901
9902    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9903            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9904            final int[] userIds) {
9905        mHandler.post(new Runnable() {
9906            @Override
9907            public void run() {
9908                try {
9909                    final IActivityManager am = ActivityManagerNative.getDefault();
9910                    if (am == null) return;
9911                    final int[] resolvedUserIds;
9912                    if (userIds == null) {
9913                        resolvedUserIds = am.getRunningUserIds();
9914                    } else {
9915                        resolvedUserIds = userIds;
9916                    }
9917                    for (int id : resolvedUserIds) {
9918                        final Intent intent = new Intent(action,
9919                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9920                        if (extras != null) {
9921                            intent.putExtras(extras);
9922                        }
9923                        if (targetPkg != null) {
9924                            intent.setPackage(targetPkg);
9925                        }
9926                        // Modify the UID when posting to other users
9927                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9928                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9929                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9930                            intent.putExtra(Intent.EXTRA_UID, uid);
9931                        }
9932                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9933                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9934                        if (DEBUG_BROADCASTS) {
9935                            RuntimeException here = new RuntimeException("here");
9936                            here.fillInStackTrace();
9937                            Slog.d(TAG, "Sending to user " + id + ": "
9938                                    + intent.toShortString(false, true, false, false)
9939                                    + " " + intent.getExtras(), here);
9940                        }
9941                        am.broadcastIntent(null, intent, null, finishedReceiver,
9942                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9943                                null, finishedReceiver != null, false, id);
9944                    }
9945                } catch (RemoteException ex) {
9946                }
9947            }
9948        });
9949    }
9950
9951    /**
9952     * Check if the external storage media is available. This is true if there
9953     * is a mounted external storage medium or if the external storage is
9954     * emulated.
9955     */
9956    private boolean isExternalMediaAvailable() {
9957        return mMediaMounted || Environment.isExternalStorageEmulated();
9958    }
9959
9960    @Override
9961    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9962        // writer
9963        synchronized (mPackages) {
9964            if (!isExternalMediaAvailable()) {
9965                // If the external storage is no longer mounted at this point,
9966                // the caller may not have been able to delete all of this
9967                // packages files and can not delete any more.  Bail.
9968                return null;
9969            }
9970            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9971            if (lastPackage != null) {
9972                pkgs.remove(lastPackage);
9973            }
9974            if (pkgs.size() > 0) {
9975                return pkgs.get(0);
9976            }
9977        }
9978        return null;
9979    }
9980
9981    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9982        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9983                userId, andCode ? 1 : 0, packageName);
9984        if (mSystemReady) {
9985            msg.sendToTarget();
9986        } else {
9987            if (mPostSystemReadyMessages == null) {
9988                mPostSystemReadyMessages = new ArrayList<>();
9989            }
9990            mPostSystemReadyMessages.add(msg);
9991        }
9992    }
9993
9994    void startCleaningPackages() {
9995        // reader
9996        synchronized (mPackages) {
9997            if (!isExternalMediaAvailable()) {
9998                return;
9999            }
10000            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10001                return;
10002            }
10003        }
10004        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10005        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10006        IActivityManager am = ActivityManagerNative.getDefault();
10007        if (am != null) {
10008            try {
10009                am.startService(null, intent, null, mContext.getOpPackageName(),
10010                        UserHandle.USER_SYSTEM);
10011            } catch (RemoteException e) {
10012            }
10013        }
10014    }
10015
10016    @Override
10017    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10018            int installFlags, String installerPackageName, VerificationParams verificationParams,
10019            String packageAbiOverride) {
10020        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10021                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10022    }
10023
10024    @Override
10025    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10026            int installFlags, String installerPackageName, VerificationParams verificationParams,
10027            String packageAbiOverride, int userId) {
10028        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10029
10030        final int callingUid = Binder.getCallingUid();
10031        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10032
10033        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10034            try {
10035                if (observer != null) {
10036                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10037                }
10038            } catch (RemoteException re) {
10039            }
10040            return;
10041        }
10042
10043        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10044            installFlags |= PackageManager.INSTALL_FROM_ADB;
10045
10046        } else {
10047            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10048            // about installerPackageName.
10049
10050            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10051            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10052        }
10053
10054        UserHandle user;
10055        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10056            user = UserHandle.ALL;
10057        } else {
10058            user = new UserHandle(userId);
10059        }
10060
10061        // Only system components can circumvent runtime permissions when installing.
10062        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10063                && mContext.checkCallingOrSelfPermission(Manifest.permission
10064                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10065            throw new SecurityException("You need the "
10066                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10067                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10068        }
10069
10070        verificationParams.setInstallerUid(callingUid);
10071
10072        final File originFile = new File(originPath);
10073        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10074
10075        final Message msg = mHandler.obtainMessage(INIT_COPY);
10076        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10077                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10078        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10079        msg.obj = params;
10080
10081        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10082                System.identityHashCode(msg.obj));
10083        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10084                System.identityHashCode(msg.obj));
10085
10086        mHandler.sendMessage(msg);
10087    }
10088
10089    void installStage(String packageName, File stagedDir, String stagedCid,
10090            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10091            String installerPackageName, int installerUid, UserHandle user) {
10092        if (DEBUG_EPHEMERAL) {
10093            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10094                Slog.d(TAG, "Ephemeral install of " + packageName);
10095            }
10096        }
10097        final VerificationParams verifParams = new VerificationParams(
10098                null, sessionParams.originatingUri, sessionParams.referrerUri,
10099                sessionParams.originatingUid);
10100        verifParams.setInstallerUid(installerUid);
10101
10102        final OriginInfo origin;
10103        if (stagedDir != null) {
10104            origin = OriginInfo.fromStagedFile(stagedDir);
10105        } else {
10106            origin = OriginInfo.fromStagedContainer(stagedCid);
10107        }
10108
10109        final Message msg = mHandler.obtainMessage(INIT_COPY);
10110        final InstallParams params = new InstallParams(origin, null, observer,
10111                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10112                verifParams, user, sessionParams.abiOverride,
10113                sessionParams.grantedRuntimePermissions);
10114        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10115        msg.obj = params;
10116
10117        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10118                System.identityHashCode(msg.obj));
10119        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10120                System.identityHashCode(msg.obj));
10121
10122        mHandler.sendMessage(msg);
10123    }
10124
10125    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10126        Bundle extras = new Bundle(1);
10127        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10128
10129        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10130                packageName, extras, 0, null, null, new int[] {userId});
10131        try {
10132            IActivityManager am = ActivityManagerNative.getDefault();
10133            final boolean isSystem =
10134                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10135            if (isSystem && am.isUserRunning(userId, 0)) {
10136                // The just-installed/enabled app is bundled on the system, so presumed
10137                // to be able to run automatically without needing an explicit launch.
10138                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10139                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10140                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10141                        .setPackage(packageName);
10142                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10143                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10144            }
10145        } catch (RemoteException e) {
10146            // shouldn't happen
10147            Slog.w(TAG, "Unable to bootstrap installed package", e);
10148        }
10149    }
10150
10151    @Override
10152    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10153            int userId) {
10154        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10155        PackageSetting pkgSetting;
10156        final int uid = Binder.getCallingUid();
10157        enforceCrossUserPermission(uid, userId, true, true,
10158                "setApplicationHiddenSetting for user " + userId);
10159
10160        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10161            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10162            return false;
10163        }
10164
10165        long callingId = Binder.clearCallingIdentity();
10166        try {
10167            boolean sendAdded = false;
10168            boolean sendRemoved = false;
10169            // writer
10170            synchronized (mPackages) {
10171                pkgSetting = mSettings.mPackages.get(packageName);
10172                if (pkgSetting == null) {
10173                    return false;
10174                }
10175                if (pkgSetting.getHidden(userId) != hidden) {
10176                    pkgSetting.setHidden(hidden, userId);
10177                    mSettings.writePackageRestrictionsLPr(userId);
10178                    if (hidden) {
10179                        sendRemoved = true;
10180                    } else {
10181                        sendAdded = true;
10182                    }
10183                }
10184            }
10185            if (sendAdded) {
10186                sendPackageAddedForUser(packageName, pkgSetting, userId);
10187                return true;
10188            }
10189            if (sendRemoved) {
10190                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10191                        "hiding pkg");
10192                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10193                return true;
10194            }
10195        } finally {
10196            Binder.restoreCallingIdentity(callingId);
10197        }
10198        return false;
10199    }
10200
10201    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10202            int userId) {
10203        final PackageRemovedInfo info = new PackageRemovedInfo();
10204        info.removedPackage = packageName;
10205        info.removedUsers = new int[] {userId};
10206        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10207        info.sendBroadcast(false, false, false);
10208    }
10209
10210    /**
10211     * Returns true if application is not found or there was an error. Otherwise it returns
10212     * the hidden state of the package for the given user.
10213     */
10214    @Override
10215    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10216        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10217        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10218                false, "getApplicationHidden for user " + userId);
10219        PackageSetting pkgSetting;
10220        long callingId = Binder.clearCallingIdentity();
10221        try {
10222            // writer
10223            synchronized (mPackages) {
10224                pkgSetting = mSettings.mPackages.get(packageName);
10225                if (pkgSetting == null) {
10226                    return true;
10227                }
10228                return pkgSetting.getHidden(userId);
10229            }
10230        } finally {
10231            Binder.restoreCallingIdentity(callingId);
10232        }
10233    }
10234
10235    /**
10236     * @hide
10237     */
10238    @Override
10239    public int installExistingPackageAsUser(String packageName, int userId) {
10240        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10241                null);
10242        PackageSetting pkgSetting;
10243        final int uid = Binder.getCallingUid();
10244        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10245                + userId);
10246        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10247            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10248        }
10249
10250        long callingId = Binder.clearCallingIdentity();
10251        try {
10252            boolean installed = false;
10253
10254            // writer
10255            synchronized (mPackages) {
10256                pkgSetting = mSettings.mPackages.get(packageName);
10257                if (pkgSetting == null) {
10258                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10259                }
10260                if (!pkgSetting.getInstalled(userId)) {
10261                    pkgSetting.setInstalled(true, userId);
10262                    pkgSetting.setHidden(false, userId);
10263                    mSettings.writePackageRestrictionsLPr(userId);
10264                    installed = true;
10265                }
10266            }
10267
10268            if (installed) {
10269                synchronized (mInstallLock) {
10270                    final int flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
10271                    try {
10272                        mInstaller.createAppData(pkgSetting.volumeUuid, packageName, userId, flags,
10273                                pkgSetting.appId, pkgSetting.pkg.applicationInfo.seinfo);
10274                    } catch (InstallerException e) {
10275                        throw new IllegalStateException(e);
10276                    }
10277                }
10278
10279                sendPackageAddedForUser(packageName, pkgSetting, userId);
10280            }
10281        } finally {
10282            Binder.restoreCallingIdentity(callingId);
10283        }
10284
10285        return PackageManager.INSTALL_SUCCEEDED;
10286    }
10287
10288    boolean isUserRestricted(int userId, String restrictionKey) {
10289        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10290        if (restrictions.getBoolean(restrictionKey, false)) {
10291            Log.w(TAG, "User is restricted: " + restrictionKey);
10292            return true;
10293        }
10294        return false;
10295    }
10296
10297    @Override
10298    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10299        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10300        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10301                "setPackageSuspended for user " + userId);
10302
10303        long callingId = Binder.clearCallingIdentity();
10304        try {
10305            synchronized (mPackages) {
10306                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10307                if (pkgSetting != null) {
10308                    if (pkgSetting.getSuspended(userId) != suspended) {
10309                        pkgSetting.setSuspended(suspended, userId);
10310                        mSettings.writePackageRestrictionsLPr(userId);
10311                    }
10312
10313                    // TODO:
10314                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10315                    // * remove app from recents (kill app it if it is running)
10316                    // * erase existing notifications for this app
10317                    return true;
10318                }
10319
10320                return false;
10321            }
10322        } finally {
10323            Binder.restoreCallingIdentity(callingId);
10324        }
10325    }
10326
10327    @Override
10328    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10329        mContext.enforceCallingOrSelfPermission(
10330                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10331                "Only package verification agents can verify applications");
10332
10333        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10334        final PackageVerificationResponse response = new PackageVerificationResponse(
10335                verificationCode, Binder.getCallingUid());
10336        msg.arg1 = id;
10337        msg.obj = response;
10338        mHandler.sendMessage(msg);
10339    }
10340
10341    @Override
10342    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10343            long millisecondsToDelay) {
10344        mContext.enforceCallingOrSelfPermission(
10345                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10346                "Only package verification agents can extend verification timeouts");
10347
10348        final PackageVerificationState state = mPendingVerification.get(id);
10349        final PackageVerificationResponse response = new PackageVerificationResponse(
10350                verificationCodeAtTimeout, Binder.getCallingUid());
10351
10352        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10353            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10354        }
10355        if (millisecondsToDelay < 0) {
10356            millisecondsToDelay = 0;
10357        }
10358        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10359                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10360            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10361        }
10362
10363        if ((state != null) && !state.timeoutExtended()) {
10364            state.extendTimeout();
10365
10366            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10367            msg.arg1 = id;
10368            msg.obj = response;
10369            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10370        }
10371    }
10372
10373    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10374            int verificationCode, UserHandle user) {
10375        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10376        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10377        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10378        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10379        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10380
10381        mContext.sendBroadcastAsUser(intent, user,
10382                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10383    }
10384
10385    private ComponentName matchComponentForVerifier(String packageName,
10386            List<ResolveInfo> receivers) {
10387        ActivityInfo targetReceiver = null;
10388
10389        final int NR = receivers.size();
10390        for (int i = 0; i < NR; i++) {
10391            final ResolveInfo info = receivers.get(i);
10392            if (info.activityInfo == null) {
10393                continue;
10394            }
10395
10396            if (packageName.equals(info.activityInfo.packageName)) {
10397                targetReceiver = info.activityInfo;
10398                break;
10399            }
10400        }
10401
10402        if (targetReceiver == null) {
10403            return null;
10404        }
10405
10406        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10407    }
10408
10409    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10410            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10411        if (pkgInfo.verifiers.length == 0) {
10412            return null;
10413        }
10414
10415        final int N = pkgInfo.verifiers.length;
10416        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10417        for (int i = 0; i < N; i++) {
10418            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10419
10420            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10421                    receivers);
10422            if (comp == null) {
10423                continue;
10424            }
10425
10426            final int verifierUid = getUidForVerifier(verifierInfo);
10427            if (verifierUid == -1) {
10428                continue;
10429            }
10430
10431            if (DEBUG_VERIFY) {
10432                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10433                        + " with the correct signature");
10434            }
10435            sufficientVerifiers.add(comp);
10436            verificationState.addSufficientVerifier(verifierUid);
10437        }
10438
10439        return sufficientVerifiers;
10440    }
10441
10442    private int getUidForVerifier(VerifierInfo verifierInfo) {
10443        synchronized (mPackages) {
10444            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10445            if (pkg == null) {
10446                return -1;
10447            } else if (pkg.mSignatures.length != 1) {
10448                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10449                        + " has more than one signature; ignoring");
10450                return -1;
10451            }
10452
10453            /*
10454             * If the public key of the package's signature does not match
10455             * our expected public key, then this is a different package and
10456             * we should skip.
10457             */
10458
10459            final byte[] expectedPublicKey;
10460            try {
10461                final Signature verifierSig = pkg.mSignatures[0];
10462                final PublicKey publicKey = verifierSig.getPublicKey();
10463                expectedPublicKey = publicKey.getEncoded();
10464            } catch (CertificateException e) {
10465                return -1;
10466            }
10467
10468            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10469
10470            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10471                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10472                        + " does not have the expected public key; ignoring");
10473                return -1;
10474            }
10475
10476            return pkg.applicationInfo.uid;
10477        }
10478    }
10479
10480    @Override
10481    public void finishPackageInstall(int token) {
10482        enforceSystemOrRoot("Only the system is allowed to finish installs");
10483
10484        if (DEBUG_INSTALL) {
10485            Slog.v(TAG, "BM finishing package install for " + token);
10486        }
10487        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10488
10489        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10490        mHandler.sendMessage(msg);
10491    }
10492
10493    /**
10494     * Get the verification agent timeout.
10495     *
10496     * @return verification timeout in milliseconds
10497     */
10498    private long getVerificationTimeout() {
10499        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10500                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10501                DEFAULT_VERIFICATION_TIMEOUT);
10502    }
10503
10504    /**
10505     * Get the default verification agent response code.
10506     *
10507     * @return default verification response code
10508     */
10509    private int getDefaultVerificationResponse() {
10510        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10511                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10512                DEFAULT_VERIFICATION_RESPONSE);
10513    }
10514
10515    /**
10516     * Check whether or not package verification has been enabled.
10517     *
10518     * @return true if verification should be performed
10519     */
10520    private boolean isVerificationEnabled(int userId, int installFlags) {
10521        if (!DEFAULT_VERIFY_ENABLE) {
10522            return false;
10523        }
10524        // Ephemeral apps don't get the full verification treatment
10525        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10526            if (DEBUG_EPHEMERAL) {
10527                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10528            }
10529            return false;
10530        }
10531
10532        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10533
10534        // Check if installing from ADB
10535        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10536            // Do not run verification in a test harness environment
10537            if (ActivityManager.isRunningInTestHarness()) {
10538                return false;
10539            }
10540            if (ensureVerifyAppsEnabled) {
10541                return true;
10542            }
10543            // Check if the developer does not want package verification for ADB installs
10544            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10545                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10546                return false;
10547            }
10548        }
10549
10550        if (ensureVerifyAppsEnabled) {
10551            return true;
10552        }
10553
10554        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10555                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10556    }
10557
10558    @Override
10559    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10560            throws RemoteException {
10561        mContext.enforceCallingOrSelfPermission(
10562                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10563                "Only intentfilter verification agents can verify applications");
10564
10565        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10566        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10567                Binder.getCallingUid(), verificationCode, failedDomains);
10568        msg.arg1 = id;
10569        msg.obj = response;
10570        mHandler.sendMessage(msg);
10571    }
10572
10573    @Override
10574    public int getIntentVerificationStatus(String packageName, int userId) {
10575        synchronized (mPackages) {
10576            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10577        }
10578    }
10579
10580    @Override
10581    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10582        mContext.enforceCallingOrSelfPermission(
10583                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10584
10585        boolean result = false;
10586        synchronized (mPackages) {
10587            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10588        }
10589        if (result) {
10590            scheduleWritePackageRestrictionsLocked(userId);
10591        }
10592        return result;
10593    }
10594
10595    @Override
10596    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10597        synchronized (mPackages) {
10598            return mSettings.getIntentFilterVerificationsLPr(packageName);
10599        }
10600    }
10601
10602    @Override
10603    public List<IntentFilter> getAllIntentFilters(String packageName) {
10604        if (TextUtils.isEmpty(packageName)) {
10605            return Collections.<IntentFilter>emptyList();
10606        }
10607        synchronized (mPackages) {
10608            PackageParser.Package pkg = mPackages.get(packageName);
10609            if (pkg == null || pkg.activities == null) {
10610                return Collections.<IntentFilter>emptyList();
10611            }
10612            final int count = pkg.activities.size();
10613            ArrayList<IntentFilter> result = new ArrayList<>();
10614            for (int n=0; n<count; n++) {
10615                PackageParser.Activity activity = pkg.activities.get(n);
10616                if (activity.intents != null && activity.intents.size() > 0) {
10617                    result.addAll(activity.intents);
10618                }
10619            }
10620            return result;
10621        }
10622    }
10623
10624    @Override
10625    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10626        mContext.enforceCallingOrSelfPermission(
10627                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10628
10629        synchronized (mPackages) {
10630            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10631            if (packageName != null) {
10632                result |= updateIntentVerificationStatus(packageName,
10633                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10634                        userId);
10635                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10636                        packageName, userId);
10637            }
10638            return result;
10639        }
10640    }
10641
10642    @Override
10643    public String getDefaultBrowserPackageName(int userId) {
10644        synchronized (mPackages) {
10645            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10646        }
10647    }
10648
10649    /**
10650     * Get the "allow unknown sources" setting.
10651     *
10652     * @return the current "allow unknown sources" setting
10653     */
10654    private int getUnknownSourcesSettings() {
10655        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10656                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10657                -1);
10658    }
10659
10660    @Override
10661    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10662        final int uid = Binder.getCallingUid();
10663        // writer
10664        synchronized (mPackages) {
10665            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10666            if (targetPackageSetting == null) {
10667                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10668            }
10669
10670            PackageSetting installerPackageSetting;
10671            if (installerPackageName != null) {
10672                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10673                if (installerPackageSetting == null) {
10674                    throw new IllegalArgumentException("Unknown installer package: "
10675                            + installerPackageName);
10676                }
10677            } else {
10678                installerPackageSetting = null;
10679            }
10680
10681            Signature[] callerSignature;
10682            Object obj = mSettings.getUserIdLPr(uid);
10683            if (obj != null) {
10684                if (obj instanceof SharedUserSetting) {
10685                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10686                } else if (obj instanceof PackageSetting) {
10687                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10688                } else {
10689                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10690                }
10691            } else {
10692                throw new SecurityException("Unknown calling UID: " + uid);
10693            }
10694
10695            // Verify: can't set installerPackageName to a package that is
10696            // not signed with the same cert as the caller.
10697            if (installerPackageSetting != null) {
10698                if (compareSignatures(callerSignature,
10699                        installerPackageSetting.signatures.mSignatures)
10700                        != PackageManager.SIGNATURE_MATCH) {
10701                    throw new SecurityException(
10702                            "Caller does not have same cert as new installer package "
10703                            + installerPackageName);
10704                }
10705            }
10706
10707            // Verify: if target already has an installer package, it must
10708            // be signed with the same cert as the caller.
10709            if (targetPackageSetting.installerPackageName != null) {
10710                PackageSetting setting = mSettings.mPackages.get(
10711                        targetPackageSetting.installerPackageName);
10712                // If the currently set package isn't valid, then it's always
10713                // okay to change it.
10714                if (setting != null) {
10715                    if (compareSignatures(callerSignature,
10716                            setting.signatures.mSignatures)
10717                            != PackageManager.SIGNATURE_MATCH) {
10718                        throw new SecurityException(
10719                                "Caller does not have same cert as old installer package "
10720                                + targetPackageSetting.installerPackageName);
10721                    }
10722                }
10723            }
10724
10725            // Okay!
10726            targetPackageSetting.installerPackageName = installerPackageName;
10727            scheduleWriteSettingsLocked();
10728        }
10729    }
10730
10731    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10732        // Queue up an async operation since the package installation may take a little while.
10733        mHandler.post(new Runnable() {
10734            public void run() {
10735                mHandler.removeCallbacks(this);
10736                 // Result object to be returned
10737                PackageInstalledInfo res = new PackageInstalledInfo();
10738                res.returnCode = currentStatus;
10739                res.uid = -1;
10740                res.pkg = null;
10741                res.removedInfo = new PackageRemovedInfo();
10742                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10743                    args.doPreInstall(res.returnCode);
10744                    synchronized (mInstallLock) {
10745                        installPackageTracedLI(args, res);
10746                    }
10747                    args.doPostInstall(res.returnCode, res.uid);
10748                }
10749
10750                // A restore should be performed at this point if (a) the install
10751                // succeeded, (b) the operation is not an update, and (c) the new
10752                // package has not opted out of backup participation.
10753                final boolean update = res.removedInfo.removedPackage != null;
10754                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10755                boolean doRestore = !update
10756                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10757
10758                // Set up the post-install work request bookkeeping.  This will be used
10759                // and cleaned up by the post-install event handling regardless of whether
10760                // there's a restore pass performed.  Token values are >= 1.
10761                int token;
10762                if (mNextInstallToken < 0) mNextInstallToken = 1;
10763                token = mNextInstallToken++;
10764
10765                PostInstallData data = new PostInstallData(args, res);
10766                mRunningInstalls.put(token, data);
10767                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10768
10769                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10770                    // Pass responsibility to the Backup Manager.  It will perform a
10771                    // restore if appropriate, then pass responsibility back to the
10772                    // Package Manager to run the post-install observer callbacks
10773                    // and broadcasts.
10774                    IBackupManager bm = IBackupManager.Stub.asInterface(
10775                            ServiceManager.getService(Context.BACKUP_SERVICE));
10776                    if (bm != null) {
10777                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10778                                + " to BM for possible restore");
10779                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10780                        try {
10781                            // TODO: http://b/22388012
10782                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10783                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10784                            } else {
10785                                doRestore = false;
10786                            }
10787                        } catch (RemoteException e) {
10788                            // can't happen; the backup manager is local
10789                        } catch (Exception e) {
10790                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10791                            doRestore = false;
10792                        }
10793                    } else {
10794                        Slog.e(TAG, "Backup Manager not found!");
10795                        doRestore = false;
10796                    }
10797                }
10798
10799                if (!doRestore) {
10800                    // No restore possible, or the Backup Manager was mysteriously not
10801                    // available -- just fire the post-install work request directly.
10802                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10803
10804                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10805
10806                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10807                    mHandler.sendMessage(msg);
10808                }
10809            }
10810        });
10811    }
10812
10813    private abstract class HandlerParams {
10814        private static final int MAX_RETRIES = 4;
10815
10816        /**
10817         * Number of times startCopy() has been attempted and had a non-fatal
10818         * error.
10819         */
10820        private int mRetries = 0;
10821
10822        /** User handle for the user requesting the information or installation. */
10823        private final UserHandle mUser;
10824        String traceMethod;
10825        int traceCookie;
10826
10827        HandlerParams(UserHandle user) {
10828            mUser = user;
10829        }
10830
10831        UserHandle getUser() {
10832            return mUser;
10833        }
10834
10835        HandlerParams setTraceMethod(String traceMethod) {
10836            this.traceMethod = traceMethod;
10837            return this;
10838        }
10839
10840        HandlerParams setTraceCookie(int traceCookie) {
10841            this.traceCookie = traceCookie;
10842            return this;
10843        }
10844
10845        final boolean startCopy() {
10846            boolean res;
10847            try {
10848                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10849
10850                if (++mRetries > MAX_RETRIES) {
10851                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10852                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10853                    handleServiceError();
10854                    return false;
10855                } else {
10856                    handleStartCopy();
10857                    res = true;
10858                }
10859            } catch (RemoteException e) {
10860                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10861                mHandler.sendEmptyMessage(MCS_RECONNECT);
10862                res = false;
10863            }
10864            handleReturnCode();
10865            return res;
10866        }
10867
10868        final void serviceError() {
10869            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10870            handleServiceError();
10871            handleReturnCode();
10872        }
10873
10874        abstract void handleStartCopy() throws RemoteException;
10875        abstract void handleServiceError();
10876        abstract void handleReturnCode();
10877    }
10878
10879    class MeasureParams extends HandlerParams {
10880        private final PackageStats mStats;
10881        private boolean mSuccess;
10882
10883        private final IPackageStatsObserver mObserver;
10884
10885        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10886            super(new UserHandle(stats.userHandle));
10887            mObserver = observer;
10888            mStats = stats;
10889        }
10890
10891        @Override
10892        public String toString() {
10893            return "MeasureParams{"
10894                + Integer.toHexString(System.identityHashCode(this))
10895                + " " + mStats.packageName + "}";
10896        }
10897
10898        @Override
10899        void handleStartCopy() throws RemoteException {
10900            synchronized (mInstallLock) {
10901                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10902            }
10903
10904            if (mSuccess) {
10905                final boolean mounted;
10906                if (Environment.isExternalStorageEmulated()) {
10907                    mounted = true;
10908                } else {
10909                    final String status = Environment.getExternalStorageState();
10910                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10911                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10912                }
10913
10914                if (mounted) {
10915                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10916
10917                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10918                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10919
10920                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10921                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10922
10923                    // Always subtract cache size, since it's a subdirectory
10924                    mStats.externalDataSize -= mStats.externalCacheSize;
10925
10926                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10927                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10928
10929                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10930                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10931                }
10932            }
10933        }
10934
10935        @Override
10936        void handleReturnCode() {
10937            if (mObserver != null) {
10938                try {
10939                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10940                } catch (RemoteException e) {
10941                    Slog.i(TAG, "Observer no longer exists.");
10942                }
10943            }
10944        }
10945
10946        @Override
10947        void handleServiceError() {
10948            Slog.e(TAG, "Could not measure application " + mStats.packageName
10949                            + " external storage");
10950        }
10951    }
10952
10953    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10954            throws RemoteException {
10955        long result = 0;
10956        for (File path : paths) {
10957            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10958        }
10959        return result;
10960    }
10961
10962    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10963        for (File path : paths) {
10964            try {
10965                mcs.clearDirectory(path.getAbsolutePath());
10966            } catch (RemoteException e) {
10967            }
10968        }
10969    }
10970
10971    static class OriginInfo {
10972        /**
10973         * Location where install is coming from, before it has been
10974         * copied/renamed into place. This could be a single monolithic APK
10975         * file, or a cluster directory. This location may be untrusted.
10976         */
10977        final File file;
10978        final String cid;
10979
10980        /**
10981         * Flag indicating that {@link #file} or {@link #cid} has already been
10982         * staged, meaning downstream users don't need to defensively copy the
10983         * contents.
10984         */
10985        final boolean staged;
10986
10987        /**
10988         * Flag indicating that {@link #file} or {@link #cid} is an already
10989         * installed app that is being moved.
10990         */
10991        final boolean existing;
10992
10993        final String resolvedPath;
10994        final File resolvedFile;
10995
10996        static OriginInfo fromNothing() {
10997            return new OriginInfo(null, null, false, false);
10998        }
10999
11000        static OriginInfo fromUntrustedFile(File file) {
11001            return new OriginInfo(file, null, false, false);
11002        }
11003
11004        static OriginInfo fromExistingFile(File file) {
11005            return new OriginInfo(file, null, false, true);
11006        }
11007
11008        static OriginInfo fromStagedFile(File file) {
11009            return new OriginInfo(file, null, true, false);
11010        }
11011
11012        static OriginInfo fromStagedContainer(String cid) {
11013            return new OriginInfo(null, cid, true, false);
11014        }
11015
11016        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11017            this.file = file;
11018            this.cid = cid;
11019            this.staged = staged;
11020            this.existing = existing;
11021
11022            if (cid != null) {
11023                resolvedPath = PackageHelper.getSdDir(cid);
11024                resolvedFile = new File(resolvedPath);
11025            } else if (file != null) {
11026                resolvedPath = file.getAbsolutePath();
11027                resolvedFile = file;
11028            } else {
11029                resolvedPath = null;
11030                resolvedFile = null;
11031            }
11032        }
11033    }
11034
11035    static class MoveInfo {
11036        final int moveId;
11037        final String fromUuid;
11038        final String toUuid;
11039        final String packageName;
11040        final String dataAppName;
11041        final int appId;
11042        final String seinfo;
11043
11044        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11045                String dataAppName, int appId, String seinfo) {
11046            this.moveId = moveId;
11047            this.fromUuid = fromUuid;
11048            this.toUuid = toUuid;
11049            this.packageName = packageName;
11050            this.dataAppName = dataAppName;
11051            this.appId = appId;
11052            this.seinfo = seinfo;
11053        }
11054    }
11055
11056    class InstallParams extends HandlerParams {
11057        final OriginInfo origin;
11058        final MoveInfo move;
11059        final IPackageInstallObserver2 observer;
11060        int installFlags;
11061        final String installerPackageName;
11062        final String volumeUuid;
11063        final VerificationParams verificationParams;
11064        private InstallArgs mArgs;
11065        private int mRet;
11066        final String packageAbiOverride;
11067        final String[] grantedRuntimePermissions;
11068
11069        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11070                int installFlags, String installerPackageName, String volumeUuid,
11071                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11072                String[] grantedPermissions) {
11073            super(user);
11074            this.origin = origin;
11075            this.move = move;
11076            this.observer = observer;
11077            this.installFlags = installFlags;
11078            this.installerPackageName = installerPackageName;
11079            this.volumeUuid = volumeUuid;
11080            this.verificationParams = verificationParams;
11081            this.packageAbiOverride = packageAbiOverride;
11082            this.grantedRuntimePermissions = grantedPermissions;
11083        }
11084
11085        @Override
11086        public String toString() {
11087            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11088                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11089        }
11090
11091        private int installLocationPolicy(PackageInfoLite pkgLite) {
11092            String packageName = pkgLite.packageName;
11093            int installLocation = pkgLite.installLocation;
11094            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11095            // reader
11096            synchronized (mPackages) {
11097                PackageParser.Package pkg = mPackages.get(packageName);
11098                if (pkg != null) {
11099                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11100                        // Check for downgrading.
11101                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11102                            try {
11103                                checkDowngrade(pkg, pkgLite);
11104                            } catch (PackageManagerException e) {
11105                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11106                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11107                            }
11108                        }
11109                        // Check for updated system application.
11110                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11111                            if (onSd) {
11112                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11113                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11114                            }
11115                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11116                        } else {
11117                            if (onSd) {
11118                                // Install flag overrides everything.
11119                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11120                            }
11121                            // If current upgrade specifies particular preference
11122                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11123                                // Application explicitly specified internal.
11124                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11125                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11126                                // App explictly prefers external. Let policy decide
11127                            } else {
11128                                // Prefer previous location
11129                                if (isExternal(pkg)) {
11130                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11131                                }
11132                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11133                            }
11134                        }
11135                    } else {
11136                        // Invalid install. Return error code
11137                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11138                    }
11139                }
11140            }
11141            // All the special cases have been taken care of.
11142            // Return result based on recommended install location.
11143            if (onSd) {
11144                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11145            }
11146            return pkgLite.recommendedInstallLocation;
11147        }
11148
11149        /*
11150         * Invoke remote method to get package information and install
11151         * location values. Override install location based on default
11152         * policy if needed and then create install arguments based
11153         * on the install location.
11154         */
11155        public void handleStartCopy() throws RemoteException {
11156            int ret = PackageManager.INSTALL_SUCCEEDED;
11157
11158            // If we're already staged, we've firmly committed to an install location
11159            if (origin.staged) {
11160                if (origin.file != null) {
11161                    installFlags |= PackageManager.INSTALL_INTERNAL;
11162                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11163                } else if (origin.cid != null) {
11164                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11165                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11166                } else {
11167                    throw new IllegalStateException("Invalid stage location");
11168                }
11169            }
11170
11171            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11172            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11173            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11174            PackageInfoLite pkgLite = null;
11175
11176            if (onInt && onSd) {
11177                // Check if both bits are set.
11178                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11179                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11180            } else if (onSd && ephemeral) {
11181                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11182                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11183            } else {
11184                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11185                        packageAbiOverride);
11186
11187                if (DEBUG_EPHEMERAL && ephemeral) {
11188                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11189                }
11190
11191                /*
11192                 * If we have too little free space, try to free cache
11193                 * before giving up.
11194                 */
11195                if (!origin.staged && pkgLite.recommendedInstallLocation
11196                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11197                    // TODO: focus freeing disk space on the target device
11198                    final StorageManager storage = StorageManager.from(mContext);
11199                    final long lowThreshold = storage.getStorageLowBytes(
11200                            Environment.getDataDirectory());
11201
11202                    final long sizeBytes = mContainerService.calculateInstalledSize(
11203                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11204
11205                    try {
11206                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11207                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11208                                installFlags, packageAbiOverride);
11209                    } catch (InstallerException e) {
11210                        Slog.w(TAG, "Failed to free cache", e);
11211                    }
11212
11213                    /*
11214                     * The cache free must have deleted the file we
11215                     * downloaded to install.
11216                     *
11217                     * TODO: fix the "freeCache" call to not delete
11218                     *       the file we care about.
11219                     */
11220                    if (pkgLite.recommendedInstallLocation
11221                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11222                        pkgLite.recommendedInstallLocation
11223                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11224                    }
11225                }
11226            }
11227
11228            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11229                int loc = pkgLite.recommendedInstallLocation;
11230                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11231                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11232                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11233                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11234                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11235                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11236                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11237                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11238                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11239                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11240                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11241                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11242                } else {
11243                    // Override with defaults if needed.
11244                    loc = installLocationPolicy(pkgLite);
11245                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11246                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11247                    } else if (!onSd && !onInt) {
11248                        // Override install location with flags
11249                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11250                            // Set the flag to install on external media.
11251                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11252                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11253                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11254                            if (DEBUG_EPHEMERAL) {
11255                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11256                            }
11257                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11258                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11259                                    |PackageManager.INSTALL_INTERNAL);
11260                        } else {
11261                            // Make sure the flag for installing on external
11262                            // media is unset
11263                            installFlags |= PackageManager.INSTALL_INTERNAL;
11264                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11265                        }
11266                    }
11267                }
11268            }
11269
11270            final InstallArgs args = createInstallArgs(this);
11271            mArgs = args;
11272
11273            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11274                // TODO: http://b/22976637
11275                // Apps installed for "all" users use the device owner to verify the app
11276                UserHandle verifierUser = getUser();
11277                if (verifierUser == UserHandle.ALL) {
11278                    verifierUser = UserHandle.SYSTEM;
11279                }
11280
11281                /*
11282                 * Determine if we have any installed package verifiers. If we
11283                 * do, then we'll defer to them to verify the packages.
11284                 */
11285                final int requiredUid = mRequiredVerifierPackage == null ? -1
11286                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11287                                verifierUser.getIdentifier());
11288                if (!origin.existing && requiredUid != -1
11289                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11290                    final Intent verification = new Intent(
11291                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11292                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11293                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11294                            PACKAGE_MIME_TYPE);
11295                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11296
11297                    // Query all live verifiers based on current user state
11298                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11299                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11300
11301                    if (DEBUG_VERIFY) {
11302                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11303                                + verification.toString() + " with " + pkgLite.verifiers.length
11304                                + " optional verifiers");
11305                    }
11306
11307                    final int verificationId = mPendingVerificationToken++;
11308
11309                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11310
11311                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11312                            installerPackageName);
11313
11314                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11315                            installFlags);
11316
11317                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11318                            pkgLite.packageName);
11319
11320                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11321                            pkgLite.versionCode);
11322
11323                    if (verificationParams != null) {
11324                        if (verificationParams.getVerificationURI() != null) {
11325                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11326                                 verificationParams.getVerificationURI());
11327                        }
11328                        if (verificationParams.getOriginatingURI() != null) {
11329                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11330                                  verificationParams.getOriginatingURI());
11331                        }
11332                        if (verificationParams.getReferrer() != null) {
11333                            verification.putExtra(Intent.EXTRA_REFERRER,
11334                                  verificationParams.getReferrer());
11335                        }
11336                        if (verificationParams.getOriginatingUid() >= 0) {
11337                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11338                                  verificationParams.getOriginatingUid());
11339                        }
11340                        if (verificationParams.getInstallerUid() >= 0) {
11341                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11342                                  verificationParams.getInstallerUid());
11343                        }
11344                    }
11345
11346                    final PackageVerificationState verificationState = new PackageVerificationState(
11347                            requiredUid, args);
11348
11349                    mPendingVerification.append(verificationId, verificationState);
11350
11351                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11352                            receivers, verificationState);
11353
11354                    /*
11355                     * If any sufficient verifiers were listed in the package
11356                     * manifest, attempt to ask them.
11357                     */
11358                    if (sufficientVerifiers != null) {
11359                        final int N = sufficientVerifiers.size();
11360                        if (N == 0) {
11361                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11362                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11363                        } else {
11364                            for (int i = 0; i < N; i++) {
11365                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11366
11367                                final Intent sufficientIntent = new Intent(verification);
11368                                sufficientIntent.setComponent(verifierComponent);
11369                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11370                            }
11371                        }
11372                    }
11373
11374                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11375                            mRequiredVerifierPackage, receivers);
11376                    if (ret == PackageManager.INSTALL_SUCCEEDED
11377                            && mRequiredVerifierPackage != null) {
11378                        Trace.asyncTraceBegin(
11379                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11380                        /*
11381                         * Send the intent to the required verification agent,
11382                         * but only start the verification timeout after the
11383                         * target BroadcastReceivers have run.
11384                         */
11385                        verification.setComponent(requiredVerifierComponent);
11386                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11387                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11388                                new BroadcastReceiver() {
11389                                    @Override
11390                                    public void onReceive(Context context, Intent intent) {
11391                                        final Message msg = mHandler
11392                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11393                                        msg.arg1 = verificationId;
11394                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11395                                    }
11396                                }, null, 0, null, null);
11397
11398                        /*
11399                         * We don't want the copy to proceed until verification
11400                         * succeeds, so null out this field.
11401                         */
11402                        mArgs = null;
11403                    }
11404                } else {
11405                    /*
11406                     * No package verification is enabled, so immediately start
11407                     * the remote call to initiate copy using temporary file.
11408                     */
11409                    ret = args.copyApk(mContainerService, true);
11410                }
11411            }
11412
11413            mRet = ret;
11414        }
11415
11416        @Override
11417        void handleReturnCode() {
11418            // If mArgs is null, then MCS couldn't be reached. When it
11419            // reconnects, it will try again to install. At that point, this
11420            // will succeed.
11421            if (mArgs != null) {
11422                processPendingInstall(mArgs, mRet);
11423            }
11424        }
11425
11426        @Override
11427        void handleServiceError() {
11428            mArgs = createInstallArgs(this);
11429            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11430        }
11431
11432        public boolean isForwardLocked() {
11433            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11434        }
11435    }
11436
11437    /**
11438     * Used during creation of InstallArgs
11439     *
11440     * @param installFlags package installation flags
11441     * @return true if should be installed on external storage
11442     */
11443    private static boolean installOnExternalAsec(int installFlags) {
11444        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11445            return false;
11446        }
11447        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11448            return true;
11449        }
11450        return false;
11451    }
11452
11453    /**
11454     * Used during creation of InstallArgs
11455     *
11456     * @param installFlags package installation flags
11457     * @return true if should be installed as forward locked
11458     */
11459    private static boolean installForwardLocked(int installFlags) {
11460        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11461    }
11462
11463    private InstallArgs createInstallArgs(InstallParams params) {
11464        if (params.move != null) {
11465            return new MoveInstallArgs(params);
11466        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11467            return new AsecInstallArgs(params);
11468        } else {
11469            return new FileInstallArgs(params);
11470        }
11471    }
11472
11473    /**
11474     * Create args that describe an existing installed package. Typically used
11475     * when cleaning up old installs, or used as a move source.
11476     */
11477    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11478            String resourcePath, String[] instructionSets) {
11479        final boolean isInAsec;
11480        if (installOnExternalAsec(installFlags)) {
11481            /* Apps on SD card are always in ASEC containers. */
11482            isInAsec = true;
11483        } else if (installForwardLocked(installFlags)
11484                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11485            /*
11486             * Forward-locked apps are only in ASEC containers if they're the
11487             * new style
11488             */
11489            isInAsec = true;
11490        } else {
11491            isInAsec = false;
11492        }
11493
11494        if (isInAsec) {
11495            return new AsecInstallArgs(codePath, instructionSets,
11496                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11497        } else {
11498            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11499        }
11500    }
11501
11502    static abstract class InstallArgs {
11503        /** @see InstallParams#origin */
11504        final OriginInfo origin;
11505        /** @see InstallParams#move */
11506        final MoveInfo move;
11507
11508        final IPackageInstallObserver2 observer;
11509        // Always refers to PackageManager flags only
11510        final int installFlags;
11511        final String installerPackageName;
11512        final String volumeUuid;
11513        final UserHandle user;
11514        final String abiOverride;
11515        final String[] installGrantPermissions;
11516        /** If non-null, drop an async trace when the install completes */
11517        final String traceMethod;
11518        final int traceCookie;
11519
11520        // The list of instruction sets supported by this app. This is currently
11521        // only used during the rmdex() phase to clean up resources. We can get rid of this
11522        // if we move dex files under the common app path.
11523        /* nullable */ String[] instructionSets;
11524
11525        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11526                int installFlags, String installerPackageName, String volumeUuid,
11527                UserHandle user, String[] instructionSets,
11528                String abiOverride, String[] installGrantPermissions,
11529                String traceMethod, int traceCookie) {
11530            this.origin = origin;
11531            this.move = move;
11532            this.installFlags = installFlags;
11533            this.observer = observer;
11534            this.installerPackageName = installerPackageName;
11535            this.volumeUuid = volumeUuid;
11536            this.user = user;
11537            this.instructionSets = instructionSets;
11538            this.abiOverride = abiOverride;
11539            this.installGrantPermissions = installGrantPermissions;
11540            this.traceMethod = traceMethod;
11541            this.traceCookie = traceCookie;
11542        }
11543
11544        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11545        abstract int doPreInstall(int status);
11546
11547        /**
11548         * Rename package into final resting place. All paths on the given
11549         * scanned package should be updated to reflect the rename.
11550         */
11551        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11552        abstract int doPostInstall(int status, int uid);
11553
11554        /** @see PackageSettingBase#codePathString */
11555        abstract String getCodePath();
11556        /** @see PackageSettingBase#resourcePathString */
11557        abstract String getResourcePath();
11558
11559        // Need installer lock especially for dex file removal.
11560        abstract void cleanUpResourcesLI();
11561        abstract boolean doPostDeleteLI(boolean delete);
11562
11563        /**
11564         * Called before the source arguments are copied. This is used mostly
11565         * for MoveParams when it needs to read the source file to put it in the
11566         * destination.
11567         */
11568        int doPreCopy() {
11569            return PackageManager.INSTALL_SUCCEEDED;
11570        }
11571
11572        /**
11573         * Called after the source arguments are copied. This is used mostly for
11574         * MoveParams when it needs to read the source file to put it in the
11575         * destination.
11576         *
11577         * @return
11578         */
11579        int doPostCopy(int uid) {
11580            return PackageManager.INSTALL_SUCCEEDED;
11581        }
11582
11583        protected boolean isFwdLocked() {
11584            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11585        }
11586
11587        protected boolean isExternalAsec() {
11588            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11589        }
11590
11591        protected boolean isEphemeral() {
11592            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11593        }
11594
11595        UserHandle getUser() {
11596            return user;
11597        }
11598    }
11599
11600    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11601        if (!allCodePaths.isEmpty()) {
11602            if (instructionSets == null) {
11603                throw new IllegalStateException("instructionSet == null");
11604            }
11605            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11606            for (String codePath : allCodePaths) {
11607                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11608                    try {
11609                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11610                    } catch (InstallerException ignored) {
11611                    }
11612                }
11613            }
11614        }
11615    }
11616
11617    /**
11618     * Logic to handle installation of non-ASEC applications, including copying
11619     * and renaming logic.
11620     */
11621    class FileInstallArgs extends InstallArgs {
11622        private File codeFile;
11623        private File resourceFile;
11624
11625        // Example topology:
11626        // /data/app/com.example/base.apk
11627        // /data/app/com.example/split_foo.apk
11628        // /data/app/com.example/lib/arm/libfoo.so
11629        // /data/app/com.example/lib/arm64/libfoo.so
11630        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11631
11632        /** New install */
11633        FileInstallArgs(InstallParams params) {
11634            super(params.origin, params.move, params.observer, params.installFlags,
11635                    params.installerPackageName, params.volumeUuid,
11636                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11637                    params.grantedRuntimePermissions,
11638                    params.traceMethod, params.traceCookie);
11639            if (isFwdLocked()) {
11640                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11641            }
11642        }
11643
11644        /** Existing install */
11645        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11646            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11647                    null, null, null, 0);
11648            this.codeFile = (codePath != null) ? new File(codePath) : null;
11649            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11650        }
11651
11652        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11653            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11654            try {
11655                return doCopyApk(imcs, temp);
11656            } finally {
11657                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11658            }
11659        }
11660
11661        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11662            if (origin.staged) {
11663                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11664                codeFile = origin.file;
11665                resourceFile = origin.file;
11666                return PackageManager.INSTALL_SUCCEEDED;
11667            }
11668
11669            try {
11670                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11671                final File tempDir =
11672                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11673                codeFile = tempDir;
11674                resourceFile = tempDir;
11675            } catch (IOException e) {
11676                Slog.w(TAG, "Failed to create copy file: " + e);
11677                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11678            }
11679
11680            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11681                @Override
11682                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11683                    if (!FileUtils.isValidExtFilename(name)) {
11684                        throw new IllegalArgumentException("Invalid filename: " + name);
11685                    }
11686                    try {
11687                        final File file = new File(codeFile, name);
11688                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11689                                O_RDWR | O_CREAT, 0644);
11690                        Os.chmod(file.getAbsolutePath(), 0644);
11691                        return new ParcelFileDescriptor(fd);
11692                    } catch (ErrnoException e) {
11693                        throw new RemoteException("Failed to open: " + e.getMessage());
11694                    }
11695                }
11696            };
11697
11698            int ret = PackageManager.INSTALL_SUCCEEDED;
11699            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11700            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11701                Slog.e(TAG, "Failed to copy package");
11702                return ret;
11703            }
11704
11705            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11706            NativeLibraryHelper.Handle handle = null;
11707            try {
11708                handle = NativeLibraryHelper.Handle.create(codeFile);
11709                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11710                        abiOverride);
11711            } catch (IOException e) {
11712                Slog.e(TAG, "Copying native libraries failed", e);
11713                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11714            } finally {
11715                IoUtils.closeQuietly(handle);
11716            }
11717
11718            return ret;
11719        }
11720
11721        int doPreInstall(int status) {
11722            if (status != PackageManager.INSTALL_SUCCEEDED) {
11723                cleanUp();
11724            }
11725            return status;
11726        }
11727
11728        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11729            if (status != PackageManager.INSTALL_SUCCEEDED) {
11730                cleanUp();
11731                return false;
11732            }
11733
11734            final File targetDir = codeFile.getParentFile();
11735            final File beforeCodeFile = codeFile;
11736            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11737
11738            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11739            try {
11740                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11741            } catch (ErrnoException e) {
11742                Slog.w(TAG, "Failed to rename", e);
11743                return false;
11744            }
11745
11746            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11747                Slog.w(TAG, "Failed to restorecon");
11748                return false;
11749            }
11750
11751            // Reflect the rename internally
11752            codeFile = afterCodeFile;
11753            resourceFile = afterCodeFile;
11754
11755            // Reflect the rename in scanned details
11756            pkg.codePath = afterCodeFile.getAbsolutePath();
11757            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11758                    pkg.baseCodePath);
11759            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11760                    pkg.splitCodePaths);
11761
11762            // Reflect the rename in app info
11763            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11764            pkg.applicationInfo.setCodePath(pkg.codePath);
11765            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11766            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11767            pkg.applicationInfo.setResourcePath(pkg.codePath);
11768            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11769            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11770
11771            return true;
11772        }
11773
11774        int doPostInstall(int status, int uid) {
11775            if (status != PackageManager.INSTALL_SUCCEEDED) {
11776                cleanUp();
11777            }
11778            return status;
11779        }
11780
11781        @Override
11782        String getCodePath() {
11783            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11784        }
11785
11786        @Override
11787        String getResourcePath() {
11788            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11789        }
11790
11791        private boolean cleanUp() {
11792            if (codeFile == null || !codeFile.exists()) {
11793                return false;
11794            }
11795
11796            removeCodePathLI(codeFile);
11797
11798            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11799                resourceFile.delete();
11800            }
11801
11802            return true;
11803        }
11804
11805        void cleanUpResourcesLI() {
11806            // Try enumerating all code paths before deleting
11807            List<String> allCodePaths = Collections.EMPTY_LIST;
11808            if (codeFile != null && codeFile.exists()) {
11809                try {
11810                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11811                    allCodePaths = pkg.getAllCodePaths();
11812                } catch (PackageParserException e) {
11813                    // Ignored; we tried our best
11814                }
11815            }
11816
11817            cleanUp();
11818            removeDexFiles(allCodePaths, instructionSets);
11819        }
11820
11821        boolean doPostDeleteLI(boolean delete) {
11822            // XXX err, shouldn't we respect the delete flag?
11823            cleanUpResourcesLI();
11824            return true;
11825        }
11826    }
11827
11828    private boolean isAsecExternal(String cid) {
11829        final String asecPath = PackageHelper.getSdFilesystem(cid);
11830        return !asecPath.startsWith(mAsecInternalPath);
11831    }
11832
11833    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11834            PackageManagerException {
11835        if (copyRet < 0) {
11836            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11837                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11838                throw new PackageManagerException(copyRet, message);
11839            }
11840        }
11841    }
11842
11843    /**
11844     * Extract the MountService "container ID" from the full code path of an
11845     * .apk.
11846     */
11847    static String cidFromCodePath(String fullCodePath) {
11848        int eidx = fullCodePath.lastIndexOf("/");
11849        String subStr1 = fullCodePath.substring(0, eidx);
11850        int sidx = subStr1.lastIndexOf("/");
11851        return subStr1.substring(sidx+1, eidx);
11852    }
11853
11854    /**
11855     * Logic to handle installation of ASEC applications, including copying and
11856     * renaming logic.
11857     */
11858    class AsecInstallArgs extends InstallArgs {
11859        static final String RES_FILE_NAME = "pkg.apk";
11860        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11861
11862        String cid;
11863        String packagePath;
11864        String resourcePath;
11865
11866        /** New install */
11867        AsecInstallArgs(InstallParams params) {
11868            super(params.origin, params.move, params.observer, params.installFlags,
11869                    params.installerPackageName, params.volumeUuid,
11870                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11871                    params.grantedRuntimePermissions,
11872                    params.traceMethod, params.traceCookie);
11873        }
11874
11875        /** Existing install */
11876        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11877                        boolean isExternal, boolean isForwardLocked) {
11878            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11879                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11880                    instructionSets, null, null, null, 0);
11881            // Hackily pretend we're still looking at a full code path
11882            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11883                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11884            }
11885
11886            // Extract cid from fullCodePath
11887            int eidx = fullCodePath.lastIndexOf("/");
11888            String subStr1 = fullCodePath.substring(0, eidx);
11889            int sidx = subStr1.lastIndexOf("/");
11890            cid = subStr1.substring(sidx+1, eidx);
11891            setMountPath(subStr1);
11892        }
11893
11894        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11895            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11896                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11897                    instructionSets, null, null, null, 0);
11898            this.cid = cid;
11899            setMountPath(PackageHelper.getSdDir(cid));
11900        }
11901
11902        void createCopyFile() {
11903            cid = mInstallerService.allocateExternalStageCidLegacy();
11904        }
11905
11906        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11907            if (origin.staged && origin.cid != null) {
11908                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11909                cid = origin.cid;
11910                setMountPath(PackageHelper.getSdDir(cid));
11911                return PackageManager.INSTALL_SUCCEEDED;
11912            }
11913
11914            if (temp) {
11915                createCopyFile();
11916            } else {
11917                /*
11918                 * Pre-emptively destroy the container since it's destroyed if
11919                 * copying fails due to it existing anyway.
11920                 */
11921                PackageHelper.destroySdDir(cid);
11922            }
11923
11924            final String newMountPath = imcs.copyPackageToContainer(
11925                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11926                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11927
11928            if (newMountPath != null) {
11929                setMountPath(newMountPath);
11930                return PackageManager.INSTALL_SUCCEEDED;
11931            } else {
11932                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11933            }
11934        }
11935
11936        @Override
11937        String getCodePath() {
11938            return packagePath;
11939        }
11940
11941        @Override
11942        String getResourcePath() {
11943            return resourcePath;
11944        }
11945
11946        int doPreInstall(int status) {
11947            if (status != PackageManager.INSTALL_SUCCEEDED) {
11948                // Destroy container
11949                PackageHelper.destroySdDir(cid);
11950            } else {
11951                boolean mounted = PackageHelper.isContainerMounted(cid);
11952                if (!mounted) {
11953                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11954                            Process.SYSTEM_UID);
11955                    if (newMountPath != null) {
11956                        setMountPath(newMountPath);
11957                    } else {
11958                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11959                    }
11960                }
11961            }
11962            return status;
11963        }
11964
11965        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11966            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11967            String newMountPath = null;
11968            if (PackageHelper.isContainerMounted(cid)) {
11969                // Unmount the container
11970                if (!PackageHelper.unMountSdDir(cid)) {
11971                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11972                    return false;
11973                }
11974            }
11975            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11976                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11977                        " which might be stale. Will try to clean up.");
11978                // Clean up the stale container and proceed to recreate.
11979                if (!PackageHelper.destroySdDir(newCacheId)) {
11980                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11981                    return false;
11982                }
11983                // Successfully cleaned up stale container. Try to rename again.
11984                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11985                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11986                            + " inspite of cleaning it up.");
11987                    return false;
11988                }
11989            }
11990            if (!PackageHelper.isContainerMounted(newCacheId)) {
11991                Slog.w(TAG, "Mounting container " + newCacheId);
11992                newMountPath = PackageHelper.mountSdDir(newCacheId,
11993                        getEncryptKey(), Process.SYSTEM_UID);
11994            } else {
11995                newMountPath = PackageHelper.getSdDir(newCacheId);
11996            }
11997            if (newMountPath == null) {
11998                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11999                return false;
12000            }
12001            Log.i(TAG, "Succesfully renamed " + cid +
12002                    " to " + newCacheId +
12003                    " at new path: " + newMountPath);
12004            cid = newCacheId;
12005
12006            final File beforeCodeFile = new File(packagePath);
12007            setMountPath(newMountPath);
12008            final File afterCodeFile = new File(packagePath);
12009
12010            // Reflect the rename in scanned details
12011            pkg.codePath = afterCodeFile.getAbsolutePath();
12012            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
12013                    pkg.baseCodePath);
12014            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
12015                    pkg.splitCodePaths);
12016
12017            // Reflect the rename in app info
12018            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12019            pkg.applicationInfo.setCodePath(pkg.codePath);
12020            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12021            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12022            pkg.applicationInfo.setResourcePath(pkg.codePath);
12023            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12024            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12025
12026            return true;
12027        }
12028
12029        private void setMountPath(String mountPath) {
12030            final File mountFile = new File(mountPath);
12031
12032            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12033            if (monolithicFile.exists()) {
12034                packagePath = monolithicFile.getAbsolutePath();
12035                if (isFwdLocked()) {
12036                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12037                } else {
12038                    resourcePath = packagePath;
12039                }
12040            } else {
12041                packagePath = mountFile.getAbsolutePath();
12042                resourcePath = packagePath;
12043            }
12044        }
12045
12046        int doPostInstall(int status, int uid) {
12047            if (status != PackageManager.INSTALL_SUCCEEDED) {
12048                cleanUp();
12049            } else {
12050                final int groupOwner;
12051                final String protectedFile;
12052                if (isFwdLocked()) {
12053                    groupOwner = UserHandle.getSharedAppGid(uid);
12054                    protectedFile = RES_FILE_NAME;
12055                } else {
12056                    groupOwner = -1;
12057                    protectedFile = null;
12058                }
12059
12060                if (uid < Process.FIRST_APPLICATION_UID
12061                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12062                    Slog.e(TAG, "Failed to finalize " + cid);
12063                    PackageHelper.destroySdDir(cid);
12064                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12065                }
12066
12067                boolean mounted = PackageHelper.isContainerMounted(cid);
12068                if (!mounted) {
12069                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12070                }
12071            }
12072            return status;
12073        }
12074
12075        private void cleanUp() {
12076            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12077
12078            // Destroy secure container
12079            PackageHelper.destroySdDir(cid);
12080        }
12081
12082        private List<String> getAllCodePaths() {
12083            final File codeFile = new File(getCodePath());
12084            if (codeFile != null && codeFile.exists()) {
12085                try {
12086                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12087                    return pkg.getAllCodePaths();
12088                } catch (PackageParserException e) {
12089                    // Ignored; we tried our best
12090                }
12091            }
12092            return Collections.EMPTY_LIST;
12093        }
12094
12095        void cleanUpResourcesLI() {
12096            // Enumerate all code paths before deleting
12097            cleanUpResourcesLI(getAllCodePaths());
12098        }
12099
12100        private void cleanUpResourcesLI(List<String> allCodePaths) {
12101            cleanUp();
12102            removeDexFiles(allCodePaths, instructionSets);
12103        }
12104
12105        String getPackageName() {
12106            return getAsecPackageName(cid);
12107        }
12108
12109        boolean doPostDeleteLI(boolean delete) {
12110            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12111            final List<String> allCodePaths = getAllCodePaths();
12112            boolean mounted = PackageHelper.isContainerMounted(cid);
12113            if (mounted) {
12114                // Unmount first
12115                if (PackageHelper.unMountSdDir(cid)) {
12116                    mounted = false;
12117                }
12118            }
12119            if (!mounted && delete) {
12120                cleanUpResourcesLI(allCodePaths);
12121            }
12122            return !mounted;
12123        }
12124
12125        @Override
12126        int doPreCopy() {
12127            if (isFwdLocked()) {
12128                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12129                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12130                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12131                }
12132            }
12133
12134            return PackageManager.INSTALL_SUCCEEDED;
12135        }
12136
12137        @Override
12138        int doPostCopy(int uid) {
12139            if (isFwdLocked()) {
12140                if (uid < Process.FIRST_APPLICATION_UID
12141                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12142                                RES_FILE_NAME)) {
12143                    Slog.e(TAG, "Failed to finalize " + cid);
12144                    PackageHelper.destroySdDir(cid);
12145                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12146                }
12147            }
12148
12149            return PackageManager.INSTALL_SUCCEEDED;
12150        }
12151    }
12152
12153    /**
12154     * Logic to handle movement of existing installed applications.
12155     */
12156    class MoveInstallArgs extends InstallArgs {
12157        private File codeFile;
12158        private File resourceFile;
12159
12160        /** New install */
12161        MoveInstallArgs(InstallParams params) {
12162            super(params.origin, params.move, params.observer, params.installFlags,
12163                    params.installerPackageName, params.volumeUuid,
12164                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12165                    params.grantedRuntimePermissions,
12166                    params.traceMethod, params.traceCookie);
12167        }
12168
12169        int copyApk(IMediaContainerService imcs, boolean temp) {
12170            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12171                    + move.fromUuid + " to " + move.toUuid);
12172            synchronized (mInstaller) {
12173                try {
12174                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12175                            move.dataAppName, move.appId, move.seinfo);
12176                } catch (InstallerException e) {
12177                    Slog.w(TAG, "Failed to move app", e);
12178                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12179                }
12180            }
12181
12182            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12183            resourceFile = codeFile;
12184            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12185
12186            return PackageManager.INSTALL_SUCCEEDED;
12187        }
12188
12189        int doPreInstall(int status) {
12190            if (status != PackageManager.INSTALL_SUCCEEDED) {
12191                cleanUp(move.toUuid);
12192            }
12193            return status;
12194        }
12195
12196        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12197            if (status != PackageManager.INSTALL_SUCCEEDED) {
12198                cleanUp(move.toUuid);
12199                return false;
12200            }
12201
12202            // Reflect the move in app info
12203            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12204            pkg.applicationInfo.setCodePath(pkg.codePath);
12205            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12206            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12207            pkg.applicationInfo.setResourcePath(pkg.codePath);
12208            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12209            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12210
12211            return true;
12212        }
12213
12214        int doPostInstall(int status, int uid) {
12215            if (status == PackageManager.INSTALL_SUCCEEDED) {
12216                cleanUp(move.fromUuid);
12217            } else {
12218                cleanUp(move.toUuid);
12219            }
12220            return status;
12221        }
12222
12223        @Override
12224        String getCodePath() {
12225            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12226        }
12227
12228        @Override
12229        String getResourcePath() {
12230            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12231        }
12232
12233        private boolean cleanUp(String volumeUuid) {
12234            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12235                    move.dataAppName);
12236            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12237            synchronized (mInstallLock) {
12238                // Clean up both app data and code
12239                removeDataDirsLI(volumeUuid, move.packageName);
12240                removeCodePathLI(codeFile);
12241            }
12242            return true;
12243        }
12244
12245        void cleanUpResourcesLI() {
12246            throw new UnsupportedOperationException();
12247        }
12248
12249        boolean doPostDeleteLI(boolean delete) {
12250            throw new UnsupportedOperationException();
12251        }
12252    }
12253
12254    static String getAsecPackageName(String packageCid) {
12255        int idx = packageCid.lastIndexOf("-");
12256        if (idx == -1) {
12257            return packageCid;
12258        }
12259        return packageCid.substring(0, idx);
12260    }
12261
12262    // Utility method used to create code paths based on package name and available index.
12263    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12264        String idxStr = "";
12265        int idx = 1;
12266        // Fall back to default value of idx=1 if prefix is not
12267        // part of oldCodePath
12268        if (oldCodePath != null) {
12269            String subStr = oldCodePath;
12270            // Drop the suffix right away
12271            if (suffix != null && subStr.endsWith(suffix)) {
12272                subStr = subStr.substring(0, subStr.length() - suffix.length());
12273            }
12274            // If oldCodePath already contains prefix find out the
12275            // ending index to either increment or decrement.
12276            int sidx = subStr.lastIndexOf(prefix);
12277            if (sidx != -1) {
12278                subStr = subStr.substring(sidx + prefix.length());
12279                if (subStr != null) {
12280                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12281                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12282                    }
12283                    try {
12284                        idx = Integer.parseInt(subStr);
12285                        if (idx <= 1) {
12286                            idx++;
12287                        } else {
12288                            idx--;
12289                        }
12290                    } catch(NumberFormatException e) {
12291                    }
12292                }
12293            }
12294        }
12295        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12296        return prefix + idxStr;
12297    }
12298
12299    private File getNextCodePath(File targetDir, String packageName) {
12300        int suffix = 1;
12301        File result;
12302        do {
12303            result = new File(targetDir, packageName + "-" + suffix);
12304            suffix++;
12305        } while (result.exists());
12306        return result;
12307    }
12308
12309    // Utility method that returns the relative package path with respect
12310    // to the installation directory. Like say for /data/data/com.test-1.apk
12311    // string com.test-1 is returned.
12312    static String deriveCodePathName(String codePath) {
12313        if (codePath == null) {
12314            return null;
12315        }
12316        final File codeFile = new File(codePath);
12317        final String name = codeFile.getName();
12318        if (codeFile.isDirectory()) {
12319            return name;
12320        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12321            final int lastDot = name.lastIndexOf('.');
12322            return name.substring(0, lastDot);
12323        } else {
12324            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12325            return null;
12326        }
12327    }
12328
12329    static class PackageInstalledInfo {
12330        String name;
12331        int uid;
12332        // The set of users that originally had this package installed.
12333        int[] origUsers;
12334        // The set of users that now have this package installed.
12335        int[] newUsers;
12336        PackageParser.Package pkg;
12337        int returnCode;
12338        String returnMsg;
12339        PackageRemovedInfo removedInfo;
12340
12341        public void setError(int code, String msg) {
12342            returnCode = code;
12343            returnMsg = msg;
12344            Slog.w(TAG, msg);
12345        }
12346
12347        public void setError(String msg, PackageParserException e) {
12348            returnCode = e.error;
12349            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12350            Slog.w(TAG, msg, e);
12351        }
12352
12353        public void setError(String msg, PackageManagerException e) {
12354            returnCode = e.error;
12355            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12356            Slog.w(TAG, msg, e);
12357        }
12358
12359        // In some error cases we want to convey more info back to the observer
12360        String origPackage;
12361        String origPermission;
12362    }
12363
12364    /*
12365     * Install a non-existing package.
12366     */
12367    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12368            UserHandle user, String installerPackageName, String volumeUuid,
12369            PackageInstalledInfo res) {
12370        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12371
12372        // Remember this for later, in case we need to rollback this install
12373        String pkgName = pkg.packageName;
12374
12375        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12376        // TODO: b/23350563
12377        final boolean dataDirExists = Environment
12378                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12379
12380        synchronized(mPackages) {
12381            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12382                // A package with the same name is already installed, though
12383                // it has been renamed to an older name.  The package we
12384                // are trying to install should be installed as an update to
12385                // the existing one, but that has not been requested, so bail.
12386                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12387                        + " without first uninstalling package running as "
12388                        + mSettings.mRenamedPackages.get(pkgName));
12389                return;
12390            }
12391            if (mPackages.containsKey(pkgName)) {
12392                // Don't allow installation over an existing package with the same name.
12393                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12394                        + " without first uninstalling.");
12395                return;
12396            }
12397        }
12398
12399        try {
12400            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12401                    System.currentTimeMillis(), user);
12402
12403            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12404            // delete the partially installed application. the data directory will have to be
12405            // restored if it was already existing
12406            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12407                // remove package from internal structures.  Note that we want deletePackageX to
12408                // delete the package data and cache directories that it created in
12409                // scanPackageLocked, unless those directories existed before we even tried to
12410                // install.
12411                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12412                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12413                                res.removedInfo, true);
12414            }
12415
12416        } catch (PackageManagerException e) {
12417            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12418        }
12419
12420        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12421    }
12422
12423    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12424        // Can't rotate keys during boot or if sharedUser.
12425        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12426                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12427            return false;
12428        }
12429        // app is using upgradeKeySets; make sure all are valid
12430        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12431        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12432        for (int i = 0; i < upgradeKeySets.length; i++) {
12433            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12434                Slog.wtf(TAG, "Package "
12435                         + (oldPs.name != null ? oldPs.name : "<null>")
12436                         + " contains upgrade-key-set reference to unknown key-set: "
12437                         + upgradeKeySets[i]
12438                         + " reverting to signatures check.");
12439                return false;
12440            }
12441        }
12442        return true;
12443    }
12444
12445    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12446        // Upgrade keysets are being used.  Determine if new package has a superset of the
12447        // required keys.
12448        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12449        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12450        for (int i = 0; i < upgradeKeySets.length; i++) {
12451            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12452            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12453                return true;
12454            }
12455        }
12456        return false;
12457    }
12458
12459    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12460            UserHandle user, String installerPackageName, String volumeUuid,
12461            PackageInstalledInfo res) {
12462        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12463
12464        final PackageParser.Package oldPackage;
12465        final String pkgName = pkg.packageName;
12466        final int[] allUsers;
12467        final boolean[] perUserInstalled;
12468
12469        // First find the old package info and check signatures
12470        synchronized(mPackages) {
12471            oldPackage = mPackages.get(pkgName);
12472            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12473            if (isEphemeral && !oldIsEphemeral) {
12474                // can't downgrade from full to ephemeral
12475                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12476                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12477                return;
12478            }
12479            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12480            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12481            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12482                if(!checkUpgradeKeySetLP(ps, pkg)) {
12483                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12484                            "New package not signed by keys specified by upgrade-keysets: "
12485                            + pkgName);
12486                    return;
12487                }
12488            } else {
12489                // default to original signature matching
12490                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12491                    != PackageManager.SIGNATURE_MATCH) {
12492                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12493                            "New package has a different signature: " + pkgName);
12494                    return;
12495                }
12496            }
12497
12498            // In case of rollback, remember per-user/profile install state
12499            allUsers = sUserManager.getUserIds();
12500            perUserInstalled = new boolean[allUsers.length];
12501            for (int i = 0; i < allUsers.length; i++) {
12502                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12503            }
12504        }
12505
12506        boolean sysPkg = (isSystemApp(oldPackage));
12507        if (sysPkg) {
12508            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12509                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12510        } else {
12511            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12512                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12513        }
12514    }
12515
12516    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12517            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12518            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12519            String volumeUuid, PackageInstalledInfo res) {
12520        String pkgName = deletedPackage.packageName;
12521        boolean deletedPkg = true;
12522        boolean updatedSettings = false;
12523
12524        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12525                + deletedPackage);
12526        long origUpdateTime;
12527        if (pkg.mExtras != null) {
12528            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12529        } else {
12530            origUpdateTime = 0;
12531        }
12532
12533        // First delete the existing package while retaining the data directory
12534        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12535                res.removedInfo, true)) {
12536            // If the existing package wasn't successfully deleted
12537            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12538            deletedPkg = false;
12539        } else {
12540            // Successfully deleted the old package; proceed with replace.
12541
12542            // If deleted package lived in a container, give users a chance to
12543            // relinquish resources before killing.
12544            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12545                if (DEBUG_INSTALL) {
12546                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12547                }
12548                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12549                final ArrayList<String> pkgList = new ArrayList<String>(1);
12550                pkgList.add(deletedPackage.applicationInfo.packageName);
12551                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12552            }
12553
12554            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12555            try {
12556                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12557                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12558                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12559                        perUserInstalled, res, user);
12560                updatedSettings = true;
12561            } catch (PackageManagerException e) {
12562                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12563            }
12564        }
12565
12566        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12567            // remove package from internal structures.  Note that we want deletePackageX to
12568            // delete the package data and cache directories that it created in
12569            // scanPackageLocked, unless those directories existed before we even tried to
12570            // install.
12571            if(updatedSettings) {
12572                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12573                deletePackageLI(
12574                        pkgName, null, true, allUsers, perUserInstalled,
12575                        PackageManager.DELETE_KEEP_DATA,
12576                                res.removedInfo, true);
12577            }
12578            // Since we failed to install the new package we need to restore the old
12579            // package that we deleted.
12580            if (deletedPkg) {
12581                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12582                File restoreFile = new File(deletedPackage.codePath);
12583                // Parse old package
12584                boolean oldExternal = isExternal(deletedPackage);
12585                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12586                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12587                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12588                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12589                try {
12590                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12591                            null);
12592                } catch (PackageManagerException e) {
12593                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12594                            + e.getMessage());
12595                    return;
12596                }
12597                // Restore of old package succeeded. Update permissions.
12598                // writer
12599                synchronized (mPackages) {
12600                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12601                            UPDATE_PERMISSIONS_ALL);
12602                    // can downgrade to reader
12603                    mSettings.writeLPr();
12604                }
12605                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12606            }
12607        }
12608    }
12609
12610    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12611            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12612            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12613            String volumeUuid, PackageInstalledInfo res) {
12614        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12615                + ", old=" + deletedPackage);
12616        boolean disabledSystem = false;
12617        boolean updatedSettings = false;
12618        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12619        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12620                != 0) {
12621            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12622        }
12623        String packageName = deletedPackage.packageName;
12624        if (packageName == null) {
12625            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12626                    "Attempt to delete null packageName.");
12627            return;
12628        }
12629        PackageParser.Package oldPkg;
12630        PackageSetting oldPkgSetting;
12631        // reader
12632        synchronized (mPackages) {
12633            oldPkg = mPackages.get(packageName);
12634            oldPkgSetting = mSettings.mPackages.get(packageName);
12635            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12636                    (oldPkgSetting == null)) {
12637                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12638                        "Couldn't find package " + packageName + " information");
12639                return;
12640            }
12641        }
12642
12643        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12644
12645        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12646        res.removedInfo.removedPackage = packageName;
12647        // Remove existing system package
12648        removePackageLI(oldPkgSetting, true);
12649        // writer
12650        synchronized (mPackages) {
12651            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12652            if (!disabledSystem && deletedPackage != null) {
12653                // We didn't need to disable the .apk as a current system package,
12654                // which means we are replacing another update that is already
12655                // installed.  We need to make sure to delete the older one's .apk.
12656                res.removedInfo.args = createInstallArgsForExisting(0,
12657                        deletedPackage.applicationInfo.getCodePath(),
12658                        deletedPackage.applicationInfo.getResourcePath(),
12659                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12660            } else {
12661                res.removedInfo.args = null;
12662            }
12663        }
12664
12665        // Successfully disabled the old package. Now proceed with re-installation
12666        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12667
12668        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12669        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12670
12671        PackageParser.Package newPackage = null;
12672        try {
12673            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12674            if (newPackage.mExtras != null) {
12675                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12676                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12677                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12678
12679                // is the update attempting to change shared user? that isn't going to work...
12680                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12681                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12682                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12683                            + " to " + newPkgSetting.sharedUser);
12684                    updatedSettings = true;
12685                }
12686            }
12687
12688            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12689                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12690                        perUserInstalled, res, user);
12691                updatedSettings = true;
12692            }
12693
12694        } catch (PackageManagerException e) {
12695            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12696        }
12697
12698        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12699            // Re installation failed. Restore old information
12700            // Remove new pkg information
12701            if (newPackage != null) {
12702                removeInstalledPackageLI(newPackage, true);
12703            }
12704            // Add back the old system package
12705            try {
12706                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12707            } catch (PackageManagerException e) {
12708                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12709            }
12710            // Restore the old system information in Settings
12711            synchronized (mPackages) {
12712                if (disabledSystem) {
12713                    mSettings.enableSystemPackageLPw(packageName);
12714                }
12715                if (updatedSettings) {
12716                    mSettings.setInstallerPackageName(packageName,
12717                            oldPkgSetting.installerPackageName);
12718                }
12719                mSettings.writeLPr();
12720            }
12721        }
12722    }
12723
12724    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12725        // Collect all used permissions in the UID
12726        ArraySet<String> usedPermissions = new ArraySet<>();
12727        final int packageCount = su.packages.size();
12728        for (int i = 0; i < packageCount; i++) {
12729            PackageSetting ps = su.packages.valueAt(i);
12730            if (ps.pkg == null) {
12731                continue;
12732            }
12733            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12734            for (int j = 0; j < requestedPermCount; j++) {
12735                String permission = ps.pkg.requestedPermissions.get(j);
12736                BasePermission bp = mSettings.mPermissions.get(permission);
12737                if (bp != null) {
12738                    usedPermissions.add(permission);
12739                }
12740            }
12741        }
12742
12743        PermissionsState permissionsState = su.getPermissionsState();
12744        // Prune install permissions
12745        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12746        final int installPermCount = installPermStates.size();
12747        for (int i = installPermCount - 1; i >= 0;  i--) {
12748            PermissionState permissionState = installPermStates.get(i);
12749            if (!usedPermissions.contains(permissionState.getName())) {
12750                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12751                if (bp != null) {
12752                    permissionsState.revokeInstallPermission(bp);
12753                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12754                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12755                }
12756            }
12757        }
12758
12759        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12760
12761        // Prune runtime permissions
12762        for (int userId : allUserIds) {
12763            List<PermissionState> runtimePermStates = permissionsState
12764                    .getRuntimePermissionStates(userId);
12765            final int runtimePermCount = runtimePermStates.size();
12766            for (int i = runtimePermCount - 1; i >= 0; i--) {
12767                PermissionState permissionState = runtimePermStates.get(i);
12768                if (!usedPermissions.contains(permissionState.getName())) {
12769                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12770                    if (bp != null) {
12771                        permissionsState.revokeRuntimePermission(bp, userId);
12772                        permissionsState.updatePermissionFlags(bp, userId,
12773                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12774                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12775                                runtimePermissionChangedUserIds, userId);
12776                    }
12777                }
12778            }
12779        }
12780
12781        return runtimePermissionChangedUserIds;
12782    }
12783
12784    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12785            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12786            UserHandle user) {
12787        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12788
12789        String pkgName = newPackage.packageName;
12790        synchronized (mPackages) {
12791            //write settings. the installStatus will be incomplete at this stage.
12792            //note that the new package setting would have already been
12793            //added to mPackages. It hasn't been persisted yet.
12794            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12795            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12796            mSettings.writeLPr();
12797            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12798        }
12799
12800        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12801        synchronized (mPackages) {
12802            updatePermissionsLPw(newPackage.packageName, newPackage,
12803                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12804                            ? UPDATE_PERMISSIONS_ALL : 0));
12805            // For system-bundled packages, we assume that installing an upgraded version
12806            // of the package implies that the user actually wants to run that new code,
12807            // so we enable the package.
12808            PackageSetting ps = mSettings.mPackages.get(pkgName);
12809            if (ps != null) {
12810                if (isSystemApp(newPackage)) {
12811                    // NB: implicit assumption that system package upgrades apply to all users
12812                    if (DEBUG_INSTALL) {
12813                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12814                    }
12815                    if (res.origUsers != null) {
12816                        for (int userHandle : res.origUsers) {
12817                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12818                                    userHandle, installerPackageName);
12819                        }
12820                    }
12821                    // Also convey the prior install/uninstall state
12822                    if (allUsers != null && perUserInstalled != null) {
12823                        for (int i = 0; i < allUsers.length; i++) {
12824                            if (DEBUG_INSTALL) {
12825                                Slog.d(TAG, "    user " + allUsers[i]
12826                                        + " => " + perUserInstalled[i]);
12827                            }
12828                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12829                        }
12830                        // these install state changes will be persisted in the
12831                        // upcoming call to mSettings.writeLPr().
12832                    }
12833                }
12834                // It's implied that when a user requests installation, they want the app to be
12835                // installed and enabled.
12836                int userId = user.getIdentifier();
12837                if (userId != UserHandle.USER_ALL) {
12838                    ps.setInstalled(true, userId);
12839                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12840                }
12841            }
12842            res.name = pkgName;
12843            res.uid = newPackage.applicationInfo.uid;
12844            res.pkg = newPackage;
12845            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12846            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12847            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12848            //to update install status
12849            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12850            mSettings.writeLPr();
12851            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12852        }
12853
12854        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12855    }
12856
12857    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12858        try {
12859            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12860            installPackageLI(args, res);
12861        } finally {
12862            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12863        }
12864    }
12865
12866    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12867        final int installFlags = args.installFlags;
12868        final String installerPackageName = args.installerPackageName;
12869        final String volumeUuid = args.volumeUuid;
12870        final File tmpPackageFile = new File(args.getCodePath());
12871        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12872        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12873                || (args.volumeUuid != null));
12874        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12875        boolean replace = false;
12876        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12877        if (args.move != null) {
12878            // moving a complete application; perfom an initial scan on the new install location
12879            scanFlags |= SCAN_INITIAL;
12880        }
12881        // Result object to be returned
12882        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12883
12884        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12885
12886        // Sanity check
12887        if (ephemeral && (forwardLocked || onExternal)) {
12888            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12889                    + " external=" + onExternal);
12890            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12891            return;
12892        }
12893
12894        // Retrieve PackageSettings and parse package
12895        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12896                | PackageParser.PARSE_ENFORCE_CODE
12897                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12898                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12899                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12900        PackageParser pp = new PackageParser();
12901        pp.setSeparateProcesses(mSeparateProcesses);
12902        pp.setDisplayMetrics(mMetrics);
12903
12904        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12905        final PackageParser.Package pkg;
12906        try {
12907            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12908        } catch (PackageParserException e) {
12909            res.setError("Failed parse during installPackageLI", e);
12910            return;
12911        } finally {
12912            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12913        }
12914
12915        // Mark that we have an install time CPU ABI override.
12916        pkg.cpuAbiOverride = args.abiOverride;
12917
12918        String pkgName = res.name = pkg.packageName;
12919        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12920            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12921                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12922                return;
12923            }
12924        }
12925
12926        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12927        try {
12928            pp.collectCertificates(pkg, parseFlags);
12929        } catch (PackageParserException e) {
12930            res.setError("Failed collect during installPackageLI", e);
12931            return;
12932        } finally {
12933            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12934        }
12935
12936        // Get rid of all references to package scan path via parser.
12937        pp = null;
12938        String oldCodePath = null;
12939        boolean systemApp = false;
12940        synchronized (mPackages) {
12941            // Check if installing already existing package
12942            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12943                String oldName = mSettings.mRenamedPackages.get(pkgName);
12944                if (pkg.mOriginalPackages != null
12945                        && pkg.mOriginalPackages.contains(oldName)
12946                        && mPackages.containsKey(oldName)) {
12947                    // This package is derived from an original package,
12948                    // and this device has been updating from that original
12949                    // name.  We must continue using the original name, so
12950                    // rename the new package here.
12951                    pkg.setPackageName(oldName);
12952                    pkgName = pkg.packageName;
12953                    replace = true;
12954                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12955                            + oldName + " pkgName=" + pkgName);
12956                } else if (mPackages.containsKey(pkgName)) {
12957                    // This package, under its official name, already exists
12958                    // on the device; we should replace it.
12959                    replace = true;
12960                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12961                }
12962
12963                // Prevent apps opting out from runtime permissions
12964                if (replace) {
12965                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12966                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12967                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12968                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12969                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12970                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12971                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12972                                        + " doesn't support runtime permissions but the old"
12973                                        + " target SDK " + oldTargetSdk + " does.");
12974                        return;
12975                    }
12976                }
12977            }
12978
12979            PackageSetting ps = mSettings.mPackages.get(pkgName);
12980            if (ps != null) {
12981                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12982
12983                // Quick sanity check that we're signed correctly if updating;
12984                // we'll check this again later when scanning, but we want to
12985                // bail early here before tripping over redefined permissions.
12986                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12987                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12988                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12989                                + pkg.packageName + " upgrade keys do not match the "
12990                                + "previously installed version");
12991                        return;
12992                    }
12993                } else {
12994                    try {
12995                        verifySignaturesLP(ps, pkg);
12996                    } catch (PackageManagerException e) {
12997                        res.setError(e.error, e.getMessage());
12998                        return;
12999                    }
13000                }
13001
13002                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13003                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13004                    systemApp = (ps.pkg.applicationInfo.flags &
13005                            ApplicationInfo.FLAG_SYSTEM) != 0;
13006                }
13007                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13008            }
13009
13010            // Check whether the newly-scanned package wants to define an already-defined perm
13011            int N = pkg.permissions.size();
13012            for (int i = N-1; i >= 0; i--) {
13013                PackageParser.Permission perm = pkg.permissions.get(i);
13014                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13015                if (bp != null) {
13016                    // If the defining package is signed with our cert, it's okay.  This
13017                    // also includes the "updating the same package" case, of course.
13018                    // "updating same package" could also involve key-rotation.
13019                    final boolean sigsOk;
13020                    if (bp.sourcePackage.equals(pkg.packageName)
13021                            && (bp.packageSetting instanceof PackageSetting)
13022                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13023                                    scanFlags))) {
13024                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13025                    } else {
13026                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13027                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13028                    }
13029                    if (!sigsOk) {
13030                        // If the owning package is the system itself, we log but allow
13031                        // install to proceed; we fail the install on all other permission
13032                        // redefinitions.
13033                        if (!bp.sourcePackage.equals("android")) {
13034                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13035                                    + pkg.packageName + " attempting to redeclare permission "
13036                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13037                            res.origPermission = perm.info.name;
13038                            res.origPackage = bp.sourcePackage;
13039                            return;
13040                        } else {
13041                            Slog.w(TAG, "Package " + pkg.packageName
13042                                    + " attempting to redeclare system permission "
13043                                    + perm.info.name + "; ignoring new declaration");
13044                            pkg.permissions.remove(i);
13045                        }
13046                    }
13047                }
13048            }
13049
13050        }
13051
13052        if (systemApp) {
13053            if (onExternal) {
13054                // Abort update; system app can't be replaced with app on sdcard
13055                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13056                        "Cannot install updates to system apps on sdcard");
13057                return;
13058            } else if (ephemeral) {
13059                // Abort update; system app can't be replaced with an ephemeral app
13060                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13061                        "Cannot update a system app with an ephemeral app");
13062                return;
13063            }
13064        }
13065
13066        if (args.move != null) {
13067            // We did an in-place move, so dex is ready to roll
13068            scanFlags |= SCAN_NO_DEX;
13069            scanFlags |= SCAN_MOVE;
13070
13071            synchronized (mPackages) {
13072                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13073                if (ps == null) {
13074                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13075                            "Missing settings for moved package " + pkgName);
13076                }
13077
13078                // We moved the entire application as-is, so bring over the
13079                // previously derived ABI information.
13080                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13081                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13082            }
13083
13084        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13085            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13086            scanFlags |= SCAN_NO_DEX;
13087
13088            try {
13089                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13090                        true /* extract libs */);
13091            } catch (PackageManagerException pme) {
13092                Slog.e(TAG, "Error deriving application ABI", pme);
13093                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13094                return;
13095            }
13096        }
13097
13098        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13099            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13100            return;
13101        }
13102
13103        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13104
13105        if (replace) {
13106            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13107                    installerPackageName, volumeUuid, res);
13108        } else {
13109            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13110                    args.user, installerPackageName, volumeUuid, res);
13111        }
13112        synchronized (mPackages) {
13113            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13114            if (ps != null) {
13115                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13116            }
13117        }
13118    }
13119
13120    private void startIntentFilterVerifications(int userId, boolean replacing,
13121            PackageParser.Package pkg) {
13122        if (mIntentFilterVerifierComponent == null) {
13123            Slog.w(TAG, "No IntentFilter verification will not be done as "
13124                    + "there is no IntentFilterVerifier available!");
13125            return;
13126        }
13127
13128        final int verifierUid = getPackageUid(
13129                mIntentFilterVerifierComponent.getPackageName(),
13130                MATCH_DEBUG_TRIAGED_MISSING,
13131                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13132
13133        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13134        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13135        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13136        mHandler.sendMessage(msg);
13137    }
13138
13139    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13140            PackageParser.Package pkg) {
13141        int size = pkg.activities.size();
13142        if (size == 0) {
13143            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13144                    "No activity, so no need to verify any IntentFilter!");
13145            return;
13146        }
13147
13148        final boolean hasDomainURLs = hasDomainURLs(pkg);
13149        if (!hasDomainURLs) {
13150            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13151                    "No domain URLs, so no need to verify any IntentFilter!");
13152            return;
13153        }
13154
13155        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13156                + " if any IntentFilter from the " + size
13157                + " Activities needs verification ...");
13158
13159        int count = 0;
13160        final String packageName = pkg.packageName;
13161
13162        synchronized (mPackages) {
13163            // If this is a new install and we see that we've already run verification for this
13164            // package, we have nothing to do: it means the state was restored from backup.
13165            if (!replacing) {
13166                IntentFilterVerificationInfo ivi =
13167                        mSettings.getIntentFilterVerificationLPr(packageName);
13168                if (ivi != null) {
13169                    if (DEBUG_DOMAIN_VERIFICATION) {
13170                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13171                                + ivi.getStatusString());
13172                    }
13173                    return;
13174                }
13175            }
13176
13177            // If any filters need to be verified, then all need to be.
13178            boolean needToVerify = false;
13179            for (PackageParser.Activity a : pkg.activities) {
13180                for (ActivityIntentInfo filter : a.intents) {
13181                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13182                        if (DEBUG_DOMAIN_VERIFICATION) {
13183                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13184                        }
13185                        needToVerify = true;
13186                        break;
13187                    }
13188                }
13189            }
13190
13191            if (needToVerify) {
13192                final int verificationId = mIntentFilterVerificationToken++;
13193                for (PackageParser.Activity a : pkg.activities) {
13194                    for (ActivityIntentInfo filter : a.intents) {
13195                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13196                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13197                                    "Verification needed for IntentFilter:" + filter.toString());
13198                            mIntentFilterVerifier.addOneIntentFilterVerification(
13199                                    verifierUid, userId, verificationId, filter, packageName);
13200                            count++;
13201                        }
13202                    }
13203                }
13204            }
13205        }
13206
13207        if (count > 0) {
13208            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13209                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13210                    +  " for userId:" + userId);
13211            mIntentFilterVerifier.startVerifications(userId);
13212        } else {
13213            if (DEBUG_DOMAIN_VERIFICATION) {
13214                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13215            }
13216        }
13217    }
13218
13219    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13220        final ComponentName cn  = filter.activity.getComponentName();
13221        final String packageName = cn.getPackageName();
13222
13223        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13224                packageName);
13225        if (ivi == null) {
13226            return true;
13227        }
13228        int status = ivi.getStatus();
13229        switch (status) {
13230            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13231            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13232                return true;
13233
13234            default:
13235                // Nothing to do
13236                return false;
13237        }
13238    }
13239
13240    private static boolean isMultiArch(ApplicationInfo info) {
13241        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13242    }
13243
13244    private static boolean isExternal(PackageParser.Package pkg) {
13245        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13246    }
13247
13248    private static boolean isExternal(PackageSetting ps) {
13249        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13250    }
13251
13252    private static boolean isEphemeral(PackageParser.Package pkg) {
13253        return pkg.applicationInfo.isEphemeralApp();
13254    }
13255
13256    private static boolean isEphemeral(PackageSetting ps) {
13257        return ps.pkg != null && isEphemeral(ps.pkg);
13258    }
13259
13260    private static boolean isSystemApp(PackageParser.Package pkg) {
13261        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13262    }
13263
13264    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13265        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13266    }
13267
13268    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13269        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13270    }
13271
13272    private static boolean isSystemApp(PackageSetting ps) {
13273        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13274    }
13275
13276    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13277        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13278    }
13279
13280    private int packageFlagsToInstallFlags(PackageSetting ps) {
13281        int installFlags = 0;
13282        if (isEphemeral(ps)) {
13283            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13284        }
13285        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13286            // This existing package was an external ASEC install when we have
13287            // the external flag without a UUID
13288            installFlags |= PackageManager.INSTALL_EXTERNAL;
13289        }
13290        if (ps.isForwardLocked()) {
13291            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13292        }
13293        return installFlags;
13294    }
13295
13296    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13297        if (isExternal(pkg)) {
13298            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13299                return StorageManager.UUID_PRIMARY_PHYSICAL;
13300            } else {
13301                return pkg.volumeUuid;
13302            }
13303        } else {
13304            return StorageManager.UUID_PRIVATE_INTERNAL;
13305        }
13306    }
13307
13308    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13309        if (isExternal(pkg)) {
13310            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13311                return mSettings.getExternalVersion();
13312            } else {
13313                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13314            }
13315        } else {
13316            return mSettings.getInternalVersion();
13317        }
13318    }
13319
13320    private void deleteTempPackageFiles() {
13321        final FilenameFilter filter = new FilenameFilter() {
13322            public boolean accept(File dir, String name) {
13323                return name.startsWith("vmdl") && name.endsWith(".tmp");
13324            }
13325        };
13326        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13327            file.delete();
13328        }
13329    }
13330
13331    @Override
13332    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13333            int flags) {
13334        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13335                flags);
13336    }
13337
13338    @Override
13339    public void deletePackage(final String packageName,
13340            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13341        mContext.enforceCallingOrSelfPermission(
13342                android.Manifest.permission.DELETE_PACKAGES, null);
13343        Preconditions.checkNotNull(packageName);
13344        Preconditions.checkNotNull(observer);
13345        final int uid = Binder.getCallingUid();
13346        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13347        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13348        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13349            mContext.enforceCallingOrSelfPermission(
13350                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13351                    "deletePackage for user " + userId);
13352        }
13353
13354        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13355            try {
13356                observer.onPackageDeleted(packageName,
13357                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13358            } catch (RemoteException re) {
13359            }
13360            return;
13361        }
13362
13363        for (int currentUserId : users) {
13364            if (getBlockUninstallForUser(packageName, currentUserId)) {
13365                try {
13366                    observer.onPackageDeleted(packageName,
13367                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13368                } catch (RemoteException re) {
13369                }
13370                return;
13371            }
13372        }
13373
13374        if (DEBUG_REMOVE) {
13375            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13376        }
13377        // Queue up an async operation since the package deletion may take a little while.
13378        mHandler.post(new Runnable() {
13379            public void run() {
13380                mHandler.removeCallbacks(this);
13381                final int returnCode = deletePackageX(packageName, userId, flags);
13382                try {
13383                    observer.onPackageDeleted(packageName, returnCode, null);
13384                } catch (RemoteException e) {
13385                    Log.i(TAG, "Observer no longer exists.");
13386                } //end catch
13387            } //end run
13388        });
13389    }
13390
13391    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13392        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13393                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13394        try {
13395            if (dpm != null) {
13396                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13397                        /* callingUserOnly =*/ false);
13398                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13399                        : deviceOwnerComponentName.getPackageName();
13400                // Does the package contains the device owner?
13401                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13402                // this check is probably not needed, since DO should be registered as a device
13403                // admin on some user too. (Original bug for this: b/17657954)
13404                if (packageName.equals(deviceOwnerPackageName)) {
13405                    return true;
13406                }
13407                // Does it contain a device admin for any user?
13408                int[] users;
13409                if (userId == UserHandle.USER_ALL) {
13410                    users = sUserManager.getUserIds();
13411                } else {
13412                    users = new int[]{userId};
13413                }
13414                for (int i = 0; i < users.length; ++i) {
13415                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13416                        return true;
13417                    }
13418                }
13419            }
13420        } catch (RemoteException e) {
13421        }
13422        return false;
13423    }
13424
13425    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13426        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13427    }
13428
13429    /**
13430     *  This method is an internal method that could be get invoked either
13431     *  to delete an installed package or to clean up a failed installation.
13432     *  After deleting an installed package, a broadcast is sent to notify any
13433     *  listeners that the package has been installed. For cleaning up a failed
13434     *  installation, the broadcast is not necessary since the package's
13435     *  installation wouldn't have sent the initial broadcast either
13436     *  The key steps in deleting a package are
13437     *  deleting the package information in internal structures like mPackages,
13438     *  deleting the packages base directories through installd
13439     *  updating mSettings to reflect current status
13440     *  persisting settings for later use
13441     *  sending a broadcast if necessary
13442     */
13443    private int deletePackageX(String packageName, int userId, int flags) {
13444        final PackageRemovedInfo info = new PackageRemovedInfo();
13445        final boolean res;
13446
13447        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13448                ? UserHandle.ALL : new UserHandle(userId);
13449
13450        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13451            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13452            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13453        }
13454
13455        boolean removedForAllUsers = false;
13456        boolean systemUpdate = false;
13457
13458        PackageParser.Package uninstalledPkg;
13459
13460        // for the uninstall-updates case and restricted profiles, remember the per-
13461        // userhandle installed state
13462        int[] allUsers;
13463        boolean[] perUserInstalled;
13464        synchronized (mPackages) {
13465            uninstalledPkg = mPackages.get(packageName);
13466            PackageSetting ps = mSettings.mPackages.get(packageName);
13467            allUsers = sUserManager.getUserIds();
13468            perUserInstalled = new boolean[allUsers.length];
13469            for (int i = 0; i < allUsers.length; i++) {
13470                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13471            }
13472        }
13473
13474        synchronized (mInstallLock) {
13475            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13476            res = deletePackageLI(packageName, removeForUser,
13477                    true, allUsers, perUserInstalled,
13478                    flags | REMOVE_CHATTY, info, true);
13479            systemUpdate = info.isRemovedPackageSystemUpdate;
13480            synchronized (mPackages) {
13481                if (res) {
13482                    if (!systemUpdate && mPackages.get(packageName) == null) {
13483                        removedForAllUsers = true;
13484                    }
13485                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13486                }
13487            }
13488            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13489                    + " removedForAllUsers=" + removedForAllUsers);
13490        }
13491
13492        if (res) {
13493            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13494
13495            // If the removed package was a system update, the old system package
13496            // was re-enabled; we need to broadcast this information
13497            if (systemUpdate) {
13498                Bundle extras = new Bundle(1);
13499                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13500                        ? info.removedAppId : info.uid);
13501                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13502
13503                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13504                        extras, 0, null, null, null);
13505                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13506                        extras, 0, null, null, null);
13507                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13508                        null, 0, packageName, null, null);
13509            }
13510        }
13511        // Force a gc here.
13512        Runtime.getRuntime().gc();
13513        // Delete the resources here after sending the broadcast to let
13514        // other processes clean up before deleting resources.
13515        if (info.args != null) {
13516            synchronized (mInstallLock) {
13517                info.args.doPostDeleteLI(true);
13518            }
13519        }
13520
13521        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13522    }
13523
13524    class PackageRemovedInfo {
13525        String removedPackage;
13526        int uid = -1;
13527        int removedAppId = -1;
13528        int[] removedUsers = null;
13529        boolean isRemovedPackageSystemUpdate = false;
13530        // Clean up resources deleted packages.
13531        InstallArgs args = null;
13532
13533        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13534            Bundle extras = new Bundle(1);
13535            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13536            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13537            if (replacing) {
13538                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13539            }
13540            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13541            if (removedPackage != null) {
13542                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13543                        extras, 0, null, null, removedUsers);
13544                if (fullRemove && !replacing) {
13545                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13546                            extras, 0, null, null, removedUsers);
13547                }
13548            }
13549            if (removedAppId >= 0) {
13550                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13551                        removedUsers);
13552            }
13553        }
13554    }
13555
13556    /*
13557     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13558     * flag is not set, the data directory is removed as well.
13559     * make sure this flag is set for partially installed apps. If not its meaningless to
13560     * delete a partially installed application.
13561     */
13562    private void removePackageDataLI(PackageSetting ps,
13563            int[] allUserHandles, boolean[] perUserInstalled,
13564            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13565        String packageName = ps.name;
13566        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13567        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13568        // Retrieve object to delete permissions for shared user later on
13569        final PackageSetting deletedPs;
13570        // reader
13571        synchronized (mPackages) {
13572            deletedPs = mSettings.mPackages.get(packageName);
13573            if (outInfo != null) {
13574                outInfo.removedPackage = packageName;
13575                outInfo.removedUsers = deletedPs != null
13576                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13577                        : null;
13578            }
13579        }
13580        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13581            removeDataDirsLI(ps.volumeUuid, packageName);
13582            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13583        }
13584        // writer
13585        synchronized (mPackages) {
13586            if (deletedPs != null) {
13587                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13588                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13589                    clearDefaultBrowserIfNeeded(packageName);
13590                    if (outInfo != null) {
13591                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13592                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13593                    }
13594                    updatePermissionsLPw(deletedPs.name, null, 0);
13595                    if (deletedPs.sharedUser != null) {
13596                        // Remove permissions associated with package. Since runtime
13597                        // permissions are per user we have to kill the removed package
13598                        // or packages running under the shared user of the removed
13599                        // package if revoking the permissions requested only by the removed
13600                        // package is successful and this causes a change in gids.
13601                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13602                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13603                                    userId);
13604                            if (userIdToKill == UserHandle.USER_ALL
13605                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13606                                // If gids changed for this user, kill all affected packages.
13607                                mHandler.post(new Runnable() {
13608                                    @Override
13609                                    public void run() {
13610                                        // This has to happen with no lock held.
13611                                        killApplication(deletedPs.name, deletedPs.appId,
13612                                                KILL_APP_REASON_GIDS_CHANGED);
13613                                    }
13614                                });
13615                                break;
13616                            }
13617                        }
13618                    }
13619                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13620                }
13621                // make sure to preserve per-user disabled state if this removal was just
13622                // a downgrade of a system app to the factory package
13623                if (allUserHandles != null && perUserInstalled != null) {
13624                    if (DEBUG_REMOVE) {
13625                        Slog.d(TAG, "Propagating install state across downgrade");
13626                    }
13627                    for (int i = 0; i < allUserHandles.length; i++) {
13628                        if (DEBUG_REMOVE) {
13629                            Slog.d(TAG, "    user " + allUserHandles[i]
13630                                    + " => " + perUserInstalled[i]);
13631                        }
13632                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13633                    }
13634                }
13635            }
13636            // can downgrade to reader
13637            if (writeSettings) {
13638                // Save settings now
13639                mSettings.writeLPr();
13640            }
13641        }
13642        if (outInfo != null) {
13643            // A user ID was deleted here. Go through all users and remove it
13644            // from KeyStore.
13645            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13646        }
13647    }
13648
13649    static boolean locationIsPrivileged(File path) {
13650        try {
13651            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13652                    .getCanonicalPath();
13653            return path.getCanonicalPath().startsWith(privilegedAppDir);
13654        } catch (IOException e) {
13655            Slog.e(TAG, "Unable to access code path " + path);
13656        }
13657        return false;
13658    }
13659
13660    /*
13661     * Tries to delete system package.
13662     */
13663    private boolean deleteSystemPackageLI(PackageSetting newPs,
13664            int[] allUserHandles, boolean[] perUserInstalled,
13665            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13666        final boolean applyUserRestrictions
13667                = (allUserHandles != null) && (perUserInstalled != null);
13668        PackageSetting disabledPs = null;
13669        // Confirm if the system package has been updated
13670        // An updated system app can be deleted. This will also have to restore
13671        // the system pkg from system partition
13672        // reader
13673        synchronized (mPackages) {
13674            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13675        }
13676        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13677                + " disabledPs=" + disabledPs);
13678        if (disabledPs == null) {
13679            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13680            return false;
13681        } else if (DEBUG_REMOVE) {
13682            Slog.d(TAG, "Deleting system pkg from data partition");
13683        }
13684        if (DEBUG_REMOVE) {
13685            if (applyUserRestrictions) {
13686                Slog.d(TAG, "Remembering install states:");
13687                for (int i = 0; i < allUserHandles.length; i++) {
13688                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13689                }
13690            }
13691        }
13692        // Delete the updated package
13693        outInfo.isRemovedPackageSystemUpdate = true;
13694        if (disabledPs.versionCode < newPs.versionCode) {
13695            // Delete data for downgrades
13696            flags &= ~PackageManager.DELETE_KEEP_DATA;
13697        } else {
13698            // Preserve data by setting flag
13699            flags |= PackageManager.DELETE_KEEP_DATA;
13700        }
13701        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13702                allUserHandles, perUserInstalled, outInfo, writeSettings);
13703        if (!ret) {
13704            return false;
13705        }
13706        // writer
13707        synchronized (mPackages) {
13708            // Reinstate the old system package
13709            mSettings.enableSystemPackageLPw(newPs.name);
13710            // Remove any native libraries from the upgraded package.
13711            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13712        }
13713        // Install the system package
13714        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13715        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13716        if (locationIsPrivileged(disabledPs.codePath)) {
13717            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13718        }
13719
13720        final PackageParser.Package newPkg;
13721        try {
13722            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13723        } catch (PackageManagerException e) {
13724            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13725            return false;
13726        }
13727
13728        // writer
13729        synchronized (mPackages) {
13730            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13731
13732            // Propagate the permissions state as we do not want to drop on the floor
13733            // runtime permissions. The update permissions method below will take
13734            // care of removing obsolete permissions and grant install permissions.
13735            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13736            updatePermissionsLPw(newPkg.packageName, newPkg,
13737                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13738
13739            if (applyUserRestrictions) {
13740                if (DEBUG_REMOVE) {
13741                    Slog.d(TAG, "Propagating install state across reinstall");
13742                }
13743                for (int i = 0; i < allUserHandles.length; i++) {
13744                    if (DEBUG_REMOVE) {
13745                        Slog.d(TAG, "    user " + allUserHandles[i]
13746                                + " => " + perUserInstalled[i]);
13747                    }
13748                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13749
13750                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13751                }
13752                // Regardless of writeSettings we need to ensure that this restriction
13753                // state propagation is persisted
13754                mSettings.writeAllUsersPackageRestrictionsLPr();
13755            }
13756            // can downgrade to reader here
13757            if (writeSettings) {
13758                mSettings.writeLPr();
13759            }
13760        }
13761        return true;
13762    }
13763
13764    private boolean deleteInstalledPackageLI(PackageSetting ps,
13765            boolean deleteCodeAndResources, int flags,
13766            int[] allUserHandles, boolean[] perUserInstalled,
13767            PackageRemovedInfo outInfo, boolean writeSettings) {
13768        if (outInfo != null) {
13769            outInfo.uid = ps.appId;
13770        }
13771
13772        // Delete package data from internal structures and also remove data if flag is set
13773        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13774
13775        // Delete application code and resources
13776        if (deleteCodeAndResources && (outInfo != null)) {
13777            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13778                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13779            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13780        }
13781        return true;
13782    }
13783
13784    @Override
13785    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13786            int userId) {
13787        mContext.enforceCallingOrSelfPermission(
13788                android.Manifest.permission.DELETE_PACKAGES, null);
13789        synchronized (mPackages) {
13790            PackageSetting ps = mSettings.mPackages.get(packageName);
13791            if (ps == null) {
13792                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13793                return false;
13794            }
13795            if (!ps.getInstalled(userId)) {
13796                // Can't block uninstall for an app that is not installed or enabled.
13797                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13798                return false;
13799            }
13800            ps.setBlockUninstall(blockUninstall, userId);
13801            mSettings.writePackageRestrictionsLPr(userId);
13802        }
13803        return true;
13804    }
13805
13806    @Override
13807    public boolean getBlockUninstallForUser(String packageName, int userId) {
13808        synchronized (mPackages) {
13809            PackageSetting ps = mSettings.mPackages.get(packageName);
13810            if (ps == null) {
13811                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13812                return false;
13813            }
13814            return ps.getBlockUninstall(userId);
13815        }
13816    }
13817
13818    @Override
13819    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13820        int callingUid = Binder.getCallingUid();
13821        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13822            throw new SecurityException(
13823                    "setRequiredForSystemUser can only be run by the system or root");
13824        }
13825        synchronized (mPackages) {
13826            PackageSetting ps = mSettings.mPackages.get(packageName);
13827            if (ps == null) {
13828                Log.w(TAG, "Package doesn't exist: " + packageName);
13829                return false;
13830            }
13831            if (systemUserApp) {
13832                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13833            } else {
13834                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13835            }
13836            mSettings.writeLPr();
13837        }
13838        return true;
13839    }
13840
13841    /*
13842     * This method handles package deletion in general
13843     */
13844    private boolean deletePackageLI(String packageName, UserHandle user,
13845            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13846            int flags, PackageRemovedInfo outInfo,
13847            boolean writeSettings) {
13848        if (packageName == null) {
13849            Slog.w(TAG, "Attempt to delete null packageName.");
13850            return false;
13851        }
13852        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13853        PackageSetting ps;
13854        boolean dataOnly = false;
13855        int removeUser = -1;
13856        int appId = -1;
13857        synchronized (mPackages) {
13858            ps = mSettings.mPackages.get(packageName);
13859            if (ps == null) {
13860                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13861                return false;
13862            }
13863            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13864                    && user.getIdentifier() != UserHandle.USER_ALL) {
13865                // The caller is asking that the package only be deleted for a single
13866                // user.  To do this, we just mark its uninstalled state and delete
13867                // its data.  If this is a system app, we only allow this to happen if
13868                // they have set the special DELETE_SYSTEM_APP which requests different
13869                // semantics than normal for uninstalling system apps.
13870                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13871                final int userId = user.getIdentifier();
13872                ps.setUserState(userId,
13873                        COMPONENT_ENABLED_STATE_DEFAULT,
13874                        false, //installed
13875                        true,  //stopped
13876                        true,  //notLaunched
13877                        false, //hidden
13878                        false, //suspended
13879                        null, null, null,
13880                        false, // blockUninstall
13881                        ps.readUserState(userId).domainVerificationStatus, 0);
13882                if (!isSystemApp(ps)) {
13883                    // Do not uninstall the APK if an app should be cached
13884                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13885                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13886                        // Other user still have this package installed, so all
13887                        // we need to do is clear this user's data and save that
13888                        // it is uninstalled.
13889                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13890                        removeUser = user.getIdentifier();
13891                        appId = ps.appId;
13892                        scheduleWritePackageRestrictionsLocked(removeUser);
13893                    } else {
13894                        // We need to set it back to 'installed' so the uninstall
13895                        // broadcasts will be sent correctly.
13896                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13897                        ps.setInstalled(true, user.getIdentifier());
13898                    }
13899                } else {
13900                    // This is a system app, so we assume that the
13901                    // other users still have this package installed, so all
13902                    // we need to do is clear this user's data and save that
13903                    // it is uninstalled.
13904                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13905                    removeUser = user.getIdentifier();
13906                    appId = ps.appId;
13907                    scheduleWritePackageRestrictionsLocked(removeUser);
13908                }
13909            }
13910        }
13911
13912        if (removeUser >= 0) {
13913            // From above, we determined that we are deleting this only
13914            // for a single user.  Continue the work here.
13915            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13916            if (outInfo != null) {
13917                outInfo.removedPackage = packageName;
13918                outInfo.removedAppId = appId;
13919                outInfo.removedUsers = new int[] {removeUser};
13920            }
13921            // TODO: triage flags as part of 26466827
13922            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13923            try {
13924                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13925            } catch (InstallerException e) {
13926                Slog.w(TAG, "Failed to delete app data", e);
13927            }
13928            removeKeystoreDataIfNeeded(removeUser, appId);
13929            schedulePackageCleaning(packageName, removeUser, false);
13930            synchronized (mPackages) {
13931                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13932                    scheduleWritePackageRestrictionsLocked(removeUser);
13933                }
13934                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13935            }
13936            return true;
13937        }
13938
13939        if (dataOnly) {
13940            // Delete application data first
13941            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13942            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13943            return true;
13944        }
13945
13946        boolean ret = false;
13947        if (isSystemApp(ps)) {
13948            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13949            // When an updated system application is deleted we delete the existing resources as well and
13950            // fall back to existing code in system partition
13951            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13952                    flags, outInfo, writeSettings);
13953        } else {
13954            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13955            // Kill application pre-emptively especially for apps on sd.
13956            killApplication(packageName, ps.appId, "uninstall pkg");
13957            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13958                    allUserHandles, perUserInstalled,
13959                    outInfo, writeSettings);
13960        }
13961
13962        return ret;
13963    }
13964
13965    private final static class ClearStorageConnection implements ServiceConnection {
13966        IMediaContainerService mContainerService;
13967
13968        @Override
13969        public void onServiceConnected(ComponentName name, IBinder service) {
13970            synchronized (this) {
13971                mContainerService = IMediaContainerService.Stub.asInterface(service);
13972                notifyAll();
13973            }
13974        }
13975
13976        @Override
13977        public void onServiceDisconnected(ComponentName name) {
13978        }
13979    }
13980
13981    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13982        final boolean mounted;
13983        if (Environment.isExternalStorageEmulated()) {
13984            mounted = true;
13985        } else {
13986            final String status = Environment.getExternalStorageState();
13987
13988            mounted = status.equals(Environment.MEDIA_MOUNTED)
13989                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13990        }
13991
13992        if (!mounted) {
13993            return;
13994        }
13995
13996        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13997        int[] users;
13998        if (userId == UserHandle.USER_ALL) {
13999            users = sUserManager.getUserIds();
14000        } else {
14001            users = new int[] { userId };
14002        }
14003        final ClearStorageConnection conn = new ClearStorageConnection();
14004        if (mContext.bindServiceAsUser(
14005                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14006            try {
14007                for (int curUser : users) {
14008                    long timeout = SystemClock.uptimeMillis() + 5000;
14009                    synchronized (conn) {
14010                        long now = SystemClock.uptimeMillis();
14011                        while (conn.mContainerService == null && now < timeout) {
14012                            try {
14013                                conn.wait(timeout - now);
14014                            } catch (InterruptedException e) {
14015                            }
14016                        }
14017                    }
14018                    if (conn.mContainerService == null) {
14019                        return;
14020                    }
14021
14022                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14023                    clearDirectory(conn.mContainerService,
14024                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14025                    if (allData) {
14026                        clearDirectory(conn.mContainerService,
14027                                userEnv.buildExternalStorageAppDataDirs(packageName));
14028                        clearDirectory(conn.mContainerService,
14029                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14030                    }
14031                }
14032            } finally {
14033                mContext.unbindService(conn);
14034            }
14035        }
14036    }
14037
14038    @Override
14039    public void clearApplicationUserData(final String packageName,
14040            final IPackageDataObserver observer, final int userId) {
14041        mContext.enforceCallingOrSelfPermission(
14042                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14043        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14044        // Queue up an async operation since the package deletion may take a little while.
14045        mHandler.post(new Runnable() {
14046            public void run() {
14047                mHandler.removeCallbacks(this);
14048                final boolean succeeded;
14049                synchronized (mInstallLock) {
14050                    succeeded = clearApplicationUserDataLI(packageName, userId);
14051                }
14052                clearExternalStorageDataSync(packageName, userId, true);
14053                if (succeeded) {
14054                    // invoke DeviceStorageMonitor's update method to clear any notifications
14055                    DeviceStorageMonitorInternal
14056                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14057                    if (dsm != null) {
14058                        dsm.checkMemory();
14059                    }
14060                }
14061                if(observer != null) {
14062                    try {
14063                        observer.onRemoveCompleted(packageName, succeeded);
14064                    } catch (RemoteException e) {
14065                        Log.i(TAG, "Observer no longer exists.");
14066                    }
14067                } //end if observer
14068            } //end run
14069        });
14070    }
14071
14072    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14073        if (packageName == null) {
14074            Slog.w(TAG, "Attempt to delete null packageName.");
14075            return false;
14076        }
14077
14078        // Try finding details about the requested package
14079        PackageParser.Package pkg;
14080        synchronized (mPackages) {
14081            pkg = mPackages.get(packageName);
14082            if (pkg == null) {
14083                final PackageSetting ps = mSettings.mPackages.get(packageName);
14084                if (ps != null) {
14085                    pkg = ps.pkg;
14086                }
14087            }
14088
14089            if (pkg == null) {
14090                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14091                return false;
14092            }
14093
14094            PackageSetting ps = (PackageSetting) pkg.mExtras;
14095            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14096        }
14097
14098        // Always delete data directories for package, even if we found no other
14099        // record of app. This helps users recover from UID mismatches without
14100        // resorting to a full data wipe.
14101        // TODO: triage flags as part of 26466827
14102        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14103        try {
14104            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14105        } catch (InstallerException e) {
14106            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14107            return false;
14108        }
14109
14110        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14111        removeKeystoreDataIfNeeded(userId, appId);
14112
14113        // Create a native library symlink only if we have native libraries
14114        // and if the native libraries are 32 bit libraries. We do not provide
14115        // this symlink for 64 bit libraries.
14116        if (pkg.applicationInfo.primaryCpuAbi != null &&
14117                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14118            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14119            try {
14120                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14121                        nativeLibPath, userId);
14122            } catch (InstallerException e) {
14123                Slog.w(TAG, "Failed linking native library dir", e);
14124                return false;
14125            }
14126        }
14127
14128        return true;
14129    }
14130
14131    /**
14132     * Reverts user permission state changes (permissions and flags) in
14133     * all packages for a given user.
14134     *
14135     * @param userId The device user for which to do a reset.
14136     */
14137    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14138        final int packageCount = mPackages.size();
14139        for (int i = 0; i < packageCount; i++) {
14140            PackageParser.Package pkg = mPackages.valueAt(i);
14141            PackageSetting ps = (PackageSetting) pkg.mExtras;
14142            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14143        }
14144    }
14145
14146    /**
14147     * Reverts user permission state changes (permissions and flags).
14148     *
14149     * @param ps The package for which to reset.
14150     * @param userId The device user for which to do a reset.
14151     */
14152    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14153            final PackageSetting ps, final int userId) {
14154        if (ps.pkg == null) {
14155            return;
14156        }
14157
14158        // These are flags that can change base on user actions.
14159        final int userSettableMask = FLAG_PERMISSION_USER_SET
14160                | FLAG_PERMISSION_USER_FIXED
14161                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14162                | FLAG_PERMISSION_REVIEW_REQUIRED;
14163
14164        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14165                | FLAG_PERMISSION_POLICY_FIXED;
14166
14167        boolean writeInstallPermissions = false;
14168        boolean writeRuntimePermissions = false;
14169
14170        final int permissionCount = ps.pkg.requestedPermissions.size();
14171        for (int i = 0; i < permissionCount; i++) {
14172            String permission = ps.pkg.requestedPermissions.get(i);
14173
14174            BasePermission bp = mSettings.mPermissions.get(permission);
14175            if (bp == null) {
14176                continue;
14177            }
14178
14179            // If shared user we just reset the state to which only this app contributed.
14180            if (ps.sharedUser != null) {
14181                boolean used = false;
14182                final int packageCount = ps.sharedUser.packages.size();
14183                for (int j = 0; j < packageCount; j++) {
14184                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14185                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14186                            && pkg.pkg.requestedPermissions.contains(permission)) {
14187                        used = true;
14188                        break;
14189                    }
14190                }
14191                if (used) {
14192                    continue;
14193                }
14194            }
14195
14196            PermissionsState permissionsState = ps.getPermissionsState();
14197
14198            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14199
14200            // Always clear the user settable flags.
14201            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14202                    bp.name) != null;
14203            // If permission review is enabled and this is a legacy app, mark the
14204            // permission as requiring a review as this is the initial state.
14205            int flags = 0;
14206            if (Build.PERMISSIONS_REVIEW_REQUIRED
14207                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14208                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14209            }
14210            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14211                if (hasInstallState) {
14212                    writeInstallPermissions = true;
14213                } else {
14214                    writeRuntimePermissions = true;
14215                }
14216            }
14217
14218            // Below is only runtime permission handling.
14219            if (!bp.isRuntime()) {
14220                continue;
14221            }
14222
14223            // Never clobber system or policy.
14224            if ((oldFlags & policyOrSystemFlags) != 0) {
14225                continue;
14226            }
14227
14228            // If this permission was granted by default, make sure it is.
14229            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14230                if (permissionsState.grantRuntimePermission(bp, userId)
14231                        != PERMISSION_OPERATION_FAILURE) {
14232                    writeRuntimePermissions = true;
14233                }
14234            // If permission review is enabled the permissions for a legacy apps
14235            // are represented as constantly granted runtime ones, so don't revoke.
14236            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14237                // Otherwise, reset the permission.
14238                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14239                switch (revokeResult) {
14240                    case PERMISSION_OPERATION_SUCCESS: {
14241                        writeRuntimePermissions = true;
14242                    } break;
14243
14244                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14245                        writeRuntimePermissions = true;
14246                        final int appId = ps.appId;
14247                        mHandler.post(new Runnable() {
14248                            @Override
14249                            public void run() {
14250                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14251                            }
14252                        });
14253                    } break;
14254                }
14255            }
14256        }
14257
14258        // Synchronously write as we are taking permissions away.
14259        if (writeRuntimePermissions) {
14260            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14261        }
14262
14263        // Synchronously write as we are taking permissions away.
14264        if (writeInstallPermissions) {
14265            mSettings.writeLPr();
14266        }
14267    }
14268
14269    /**
14270     * Remove entries from the keystore daemon. Will only remove it if the
14271     * {@code appId} is valid.
14272     */
14273    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14274        if (appId < 0) {
14275            return;
14276        }
14277
14278        final KeyStore keyStore = KeyStore.getInstance();
14279        if (keyStore != null) {
14280            if (userId == UserHandle.USER_ALL) {
14281                for (final int individual : sUserManager.getUserIds()) {
14282                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14283                }
14284            } else {
14285                keyStore.clearUid(UserHandle.getUid(userId, appId));
14286            }
14287        } else {
14288            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14289        }
14290    }
14291
14292    @Override
14293    public void deleteApplicationCacheFiles(final String packageName,
14294            final IPackageDataObserver observer) {
14295        mContext.enforceCallingOrSelfPermission(
14296                android.Manifest.permission.DELETE_CACHE_FILES, null);
14297        // Queue up an async operation since the package deletion may take a little while.
14298        final int userId = UserHandle.getCallingUserId();
14299        mHandler.post(new Runnable() {
14300            public void run() {
14301                mHandler.removeCallbacks(this);
14302                final boolean succeded;
14303                synchronized (mInstallLock) {
14304                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14305                }
14306                clearExternalStorageDataSync(packageName, userId, false);
14307                if (observer != null) {
14308                    try {
14309                        observer.onRemoveCompleted(packageName, succeded);
14310                    } catch (RemoteException e) {
14311                        Log.i(TAG, "Observer no longer exists.");
14312                    }
14313                } //end if observer
14314            } //end run
14315        });
14316    }
14317
14318    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14319        if (packageName == null) {
14320            Slog.w(TAG, "Attempt to delete null packageName.");
14321            return false;
14322        }
14323        PackageParser.Package p;
14324        synchronized (mPackages) {
14325            p = mPackages.get(packageName);
14326        }
14327        if (p == null) {
14328            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14329            return false;
14330        }
14331        final ApplicationInfo applicationInfo = p.applicationInfo;
14332        if (applicationInfo == null) {
14333            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14334            return false;
14335        }
14336        // TODO: triage flags as part of 26466827
14337        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14338        try {
14339            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14340                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14341        } catch (InstallerException e) {
14342            Slog.w(TAG, "Couldn't remove cache files for package "
14343                    + packageName + " u" + userId, e);
14344            return false;
14345        }
14346        return true;
14347    }
14348
14349    @Override
14350    public void getPackageSizeInfo(final String packageName, int userHandle,
14351            final IPackageStatsObserver observer) {
14352        mContext.enforceCallingOrSelfPermission(
14353                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14354        if (packageName == null) {
14355            throw new IllegalArgumentException("Attempt to get size of null packageName");
14356        }
14357
14358        PackageStats stats = new PackageStats(packageName, userHandle);
14359
14360        /*
14361         * Queue up an async operation since the package measurement may take a
14362         * little while.
14363         */
14364        Message msg = mHandler.obtainMessage(INIT_COPY);
14365        msg.obj = new MeasureParams(stats, observer);
14366        mHandler.sendMessage(msg);
14367    }
14368
14369    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14370            PackageStats pStats) {
14371        if (packageName == null) {
14372            Slog.w(TAG, "Attempt to get size of null packageName.");
14373            return false;
14374        }
14375        PackageParser.Package p;
14376        boolean dataOnly = false;
14377        String libDirRoot = null;
14378        String asecPath = null;
14379        PackageSetting ps = null;
14380        synchronized (mPackages) {
14381            p = mPackages.get(packageName);
14382            ps = mSettings.mPackages.get(packageName);
14383            if(p == null) {
14384                dataOnly = true;
14385                if((ps == null) || (ps.pkg == null)) {
14386                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14387                    return false;
14388                }
14389                p = ps.pkg;
14390            }
14391            if (ps != null) {
14392                libDirRoot = ps.legacyNativeLibraryPathString;
14393            }
14394            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14395                final long token = Binder.clearCallingIdentity();
14396                try {
14397                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14398                    if (secureContainerId != null) {
14399                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14400                    }
14401                } finally {
14402                    Binder.restoreCallingIdentity(token);
14403                }
14404            }
14405        }
14406        String publicSrcDir = null;
14407        if(!dataOnly) {
14408            final ApplicationInfo applicationInfo = p.applicationInfo;
14409            if (applicationInfo == null) {
14410                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14411                return false;
14412            }
14413            if (p.isForwardLocked()) {
14414                publicSrcDir = applicationInfo.getBaseResourcePath();
14415            }
14416        }
14417        // TODO: extend to measure size of split APKs
14418        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14419        // not just the first level.
14420        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14421        // just the primary.
14422        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14423
14424        String apkPath;
14425        File packageDir = new File(p.codePath);
14426
14427        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14428            apkPath = packageDir.getAbsolutePath();
14429            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14430            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14431                libDirRoot = null;
14432            }
14433        } else {
14434            apkPath = p.baseCodePath;
14435        }
14436
14437        // TODO: triage flags as part of 26466827
14438        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14439        try {
14440            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14441                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14442        } catch (InstallerException e) {
14443            return false;
14444        }
14445
14446        // Fix-up for forward-locked applications in ASEC containers.
14447        if (!isExternal(p)) {
14448            pStats.codeSize += pStats.externalCodeSize;
14449            pStats.externalCodeSize = 0L;
14450        }
14451
14452        return true;
14453    }
14454
14455
14456    @Override
14457    public void addPackageToPreferred(String packageName) {
14458        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14459    }
14460
14461    @Override
14462    public void removePackageFromPreferred(String packageName) {
14463        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14464    }
14465
14466    @Override
14467    public List<PackageInfo> getPreferredPackages(int flags) {
14468        return new ArrayList<PackageInfo>();
14469    }
14470
14471    private int getUidTargetSdkVersionLockedLPr(int uid) {
14472        Object obj = mSettings.getUserIdLPr(uid);
14473        if (obj instanceof SharedUserSetting) {
14474            final SharedUserSetting sus = (SharedUserSetting) obj;
14475            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14476            final Iterator<PackageSetting> it = sus.packages.iterator();
14477            while (it.hasNext()) {
14478                final PackageSetting ps = it.next();
14479                if (ps.pkg != null) {
14480                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14481                    if (v < vers) vers = v;
14482                }
14483            }
14484            return vers;
14485        } else if (obj instanceof PackageSetting) {
14486            final PackageSetting ps = (PackageSetting) obj;
14487            if (ps.pkg != null) {
14488                return ps.pkg.applicationInfo.targetSdkVersion;
14489            }
14490        }
14491        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14492    }
14493
14494    @Override
14495    public void addPreferredActivity(IntentFilter filter, int match,
14496            ComponentName[] set, ComponentName activity, int userId) {
14497        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14498                "Adding preferred");
14499    }
14500
14501    private void addPreferredActivityInternal(IntentFilter filter, int match,
14502            ComponentName[] set, ComponentName activity, boolean always, int userId,
14503            String opname) {
14504        // writer
14505        int callingUid = Binder.getCallingUid();
14506        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14507        if (filter.countActions() == 0) {
14508            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14509            return;
14510        }
14511        synchronized (mPackages) {
14512            if (mContext.checkCallingOrSelfPermission(
14513                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14514                    != PackageManager.PERMISSION_GRANTED) {
14515                if (getUidTargetSdkVersionLockedLPr(callingUid)
14516                        < Build.VERSION_CODES.FROYO) {
14517                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14518                            + callingUid);
14519                    return;
14520                }
14521                mContext.enforceCallingOrSelfPermission(
14522                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14523            }
14524
14525            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14526            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14527                    + userId + ":");
14528            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14529            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14530            scheduleWritePackageRestrictionsLocked(userId);
14531        }
14532    }
14533
14534    @Override
14535    public void replacePreferredActivity(IntentFilter filter, int match,
14536            ComponentName[] set, ComponentName activity, int userId) {
14537        if (filter.countActions() != 1) {
14538            throw new IllegalArgumentException(
14539                    "replacePreferredActivity expects filter to have only 1 action.");
14540        }
14541        if (filter.countDataAuthorities() != 0
14542                || filter.countDataPaths() != 0
14543                || filter.countDataSchemes() > 1
14544                || filter.countDataTypes() != 0) {
14545            throw new IllegalArgumentException(
14546                    "replacePreferredActivity expects filter to have no data authorities, " +
14547                    "paths, or types; and at most one scheme.");
14548        }
14549
14550        final int callingUid = Binder.getCallingUid();
14551        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14552        synchronized (mPackages) {
14553            if (mContext.checkCallingOrSelfPermission(
14554                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14555                    != PackageManager.PERMISSION_GRANTED) {
14556                if (getUidTargetSdkVersionLockedLPr(callingUid)
14557                        < Build.VERSION_CODES.FROYO) {
14558                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14559                            + Binder.getCallingUid());
14560                    return;
14561                }
14562                mContext.enforceCallingOrSelfPermission(
14563                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14564            }
14565
14566            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14567            if (pir != null) {
14568                // Get all of the existing entries that exactly match this filter.
14569                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14570                if (existing != null && existing.size() == 1) {
14571                    PreferredActivity cur = existing.get(0);
14572                    if (DEBUG_PREFERRED) {
14573                        Slog.i(TAG, "Checking replace of preferred:");
14574                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14575                        if (!cur.mPref.mAlways) {
14576                            Slog.i(TAG, "  -- CUR; not mAlways!");
14577                        } else {
14578                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14579                            Slog.i(TAG, "  -- CUR: mSet="
14580                                    + Arrays.toString(cur.mPref.mSetComponents));
14581                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14582                            Slog.i(TAG, "  -- NEW: mMatch="
14583                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14584                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14585                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14586                        }
14587                    }
14588                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14589                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14590                            && cur.mPref.sameSet(set)) {
14591                        // Setting the preferred activity to what it happens to be already
14592                        if (DEBUG_PREFERRED) {
14593                            Slog.i(TAG, "Replacing with same preferred activity "
14594                                    + cur.mPref.mShortComponent + " for user "
14595                                    + userId + ":");
14596                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14597                        }
14598                        return;
14599                    }
14600                }
14601
14602                if (existing != null) {
14603                    if (DEBUG_PREFERRED) {
14604                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14605                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14606                    }
14607                    for (int i = 0; i < existing.size(); i++) {
14608                        PreferredActivity pa = existing.get(i);
14609                        if (DEBUG_PREFERRED) {
14610                            Slog.i(TAG, "Removing existing preferred activity "
14611                                    + pa.mPref.mComponent + ":");
14612                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14613                        }
14614                        pir.removeFilter(pa);
14615                    }
14616                }
14617            }
14618            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14619                    "Replacing preferred");
14620        }
14621    }
14622
14623    @Override
14624    public void clearPackagePreferredActivities(String packageName) {
14625        final int uid = Binder.getCallingUid();
14626        // writer
14627        synchronized (mPackages) {
14628            PackageParser.Package pkg = mPackages.get(packageName);
14629            if (pkg == null || pkg.applicationInfo.uid != uid) {
14630                if (mContext.checkCallingOrSelfPermission(
14631                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14632                        != PackageManager.PERMISSION_GRANTED) {
14633                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14634                            < Build.VERSION_CODES.FROYO) {
14635                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14636                                + Binder.getCallingUid());
14637                        return;
14638                    }
14639                    mContext.enforceCallingOrSelfPermission(
14640                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14641                }
14642            }
14643
14644            int user = UserHandle.getCallingUserId();
14645            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14646                scheduleWritePackageRestrictionsLocked(user);
14647            }
14648        }
14649    }
14650
14651    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14652    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14653        ArrayList<PreferredActivity> removed = null;
14654        boolean changed = false;
14655        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14656            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14657            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14658            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14659                continue;
14660            }
14661            Iterator<PreferredActivity> it = pir.filterIterator();
14662            while (it.hasNext()) {
14663                PreferredActivity pa = it.next();
14664                // Mark entry for removal only if it matches the package name
14665                // and the entry is of type "always".
14666                if (packageName == null ||
14667                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14668                                && pa.mPref.mAlways)) {
14669                    if (removed == null) {
14670                        removed = new ArrayList<PreferredActivity>();
14671                    }
14672                    removed.add(pa);
14673                }
14674            }
14675            if (removed != null) {
14676                for (int j=0; j<removed.size(); j++) {
14677                    PreferredActivity pa = removed.get(j);
14678                    pir.removeFilter(pa);
14679                }
14680                changed = true;
14681            }
14682        }
14683        return changed;
14684    }
14685
14686    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14687    private void clearIntentFilterVerificationsLPw(int userId) {
14688        final int packageCount = mPackages.size();
14689        for (int i = 0; i < packageCount; i++) {
14690            PackageParser.Package pkg = mPackages.valueAt(i);
14691            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14692        }
14693    }
14694
14695    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14696    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14697        if (userId == UserHandle.USER_ALL) {
14698            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14699                    sUserManager.getUserIds())) {
14700                for (int oneUserId : sUserManager.getUserIds()) {
14701                    scheduleWritePackageRestrictionsLocked(oneUserId);
14702                }
14703            }
14704        } else {
14705            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14706                scheduleWritePackageRestrictionsLocked(userId);
14707            }
14708        }
14709    }
14710
14711    void clearDefaultBrowserIfNeeded(String packageName) {
14712        for (int oneUserId : sUserManager.getUserIds()) {
14713            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14714            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14715            if (packageName.equals(defaultBrowserPackageName)) {
14716                setDefaultBrowserPackageName(null, oneUserId);
14717            }
14718        }
14719    }
14720
14721    @Override
14722    public void resetApplicationPreferences(int userId) {
14723        mContext.enforceCallingOrSelfPermission(
14724                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14725        // writer
14726        synchronized (mPackages) {
14727            final long identity = Binder.clearCallingIdentity();
14728            try {
14729                clearPackagePreferredActivitiesLPw(null, userId);
14730                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14731                // TODO: We have to reset the default SMS and Phone. This requires
14732                // significant refactoring to keep all default apps in the package
14733                // manager (cleaner but more work) or have the services provide
14734                // callbacks to the package manager to request a default app reset.
14735                applyFactoryDefaultBrowserLPw(userId);
14736                clearIntentFilterVerificationsLPw(userId);
14737                primeDomainVerificationsLPw(userId);
14738                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14739                scheduleWritePackageRestrictionsLocked(userId);
14740            } finally {
14741                Binder.restoreCallingIdentity(identity);
14742            }
14743        }
14744    }
14745
14746    @Override
14747    public int getPreferredActivities(List<IntentFilter> outFilters,
14748            List<ComponentName> outActivities, String packageName) {
14749
14750        int num = 0;
14751        final int userId = UserHandle.getCallingUserId();
14752        // reader
14753        synchronized (mPackages) {
14754            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14755            if (pir != null) {
14756                final Iterator<PreferredActivity> it = pir.filterIterator();
14757                while (it.hasNext()) {
14758                    final PreferredActivity pa = it.next();
14759                    if (packageName == null
14760                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14761                                    && pa.mPref.mAlways)) {
14762                        if (outFilters != null) {
14763                            outFilters.add(new IntentFilter(pa));
14764                        }
14765                        if (outActivities != null) {
14766                            outActivities.add(pa.mPref.mComponent);
14767                        }
14768                    }
14769                }
14770            }
14771        }
14772
14773        return num;
14774    }
14775
14776    @Override
14777    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14778            int userId) {
14779        int callingUid = Binder.getCallingUid();
14780        if (callingUid != Process.SYSTEM_UID) {
14781            throw new SecurityException(
14782                    "addPersistentPreferredActivity can only be run by the system");
14783        }
14784        if (filter.countActions() == 0) {
14785            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14786            return;
14787        }
14788        synchronized (mPackages) {
14789            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14790                    ":");
14791            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14792            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14793                    new PersistentPreferredActivity(filter, activity));
14794            scheduleWritePackageRestrictionsLocked(userId);
14795        }
14796    }
14797
14798    @Override
14799    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14800        int callingUid = Binder.getCallingUid();
14801        if (callingUid != Process.SYSTEM_UID) {
14802            throw new SecurityException(
14803                    "clearPackagePersistentPreferredActivities can only be run by the system");
14804        }
14805        ArrayList<PersistentPreferredActivity> removed = null;
14806        boolean changed = false;
14807        synchronized (mPackages) {
14808            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14809                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14810                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14811                        .valueAt(i);
14812                if (userId != thisUserId) {
14813                    continue;
14814                }
14815                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14816                while (it.hasNext()) {
14817                    PersistentPreferredActivity ppa = it.next();
14818                    // Mark entry for removal only if it matches the package name.
14819                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14820                        if (removed == null) {
14821                            removed = new ArrayList<PersistentPreferredActivity>();
14822                        }
14823                        removed.add(ppa);
14824                    }
14825                }
14826                if (removed != null) {
14827                    for (int j=0; j<removed.size(); j++) {
14828                        PersistentPreferredActivity ppa = removed.get(j);
14829                        ppir.removeFilter(ppa);
14830                    }
14831                    changed = true;
14832                }
14833            }
14834
14835            if (changed) {
14836                scheduleWritePackageRestrictionsLocked(userId);
14837            }
14838        }
14839    }
14840
14841    /**
14842     * Common machinery for picking apart a restored XML blob and passing
14843     * it to a caller-supplied functor to be applied to the running system.
14844     */
14845    private void restoreFromXml(XmlPullParser parser, int userId,
14846            String expectedStartTag, BlobXmlRestorer functor)
14847            throws IOException, XmlPullParserException {
14848        int type;
14849        while ((type = parser.next()) != XmlPullParser.START_TAG
14850                && type != XmlPullParser.END_DOCUMENT) {
14851        }
14852        if (type != XmlPullParser.START_TAG) {
14853            // oops didn't find a start tag?!
14854            if (DEBUG_BACKUP) {
14855                Slog.e(TAG, "Didn't find start tag during restore");
14856            }
14857            return;
14858        }
14859Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
14860        // this is supposed to be TAG_PREFERRED_BACKUP
14861        if (!expectedStartTag.equals(parser.getName())) {
14862            if (DEBUG_BACKUP) {
14863                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14864            }
14865            return;
14866        }
14867
14868        // skip interfering stuff, then we're aligned with the backing implementation
14869        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14870Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
14871        functor.apply(parser, userId);
14872    }
14873
14874    private interface BlobXmlRestorer {
14875        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14876    }
14877
14878    /**
14879     * Non-Binder method, support for the backup/restore mechanism: write the
14880     * full set of preferred activities in its canonical XML format.  Returns the
14881     * XML output as a byte array, or null if there is none.
14882     */
14883    @Override
14884    public byte[] getPreferredActivityBackup(int userId) {
14885        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14886            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14887        }
14888
14889        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14890        try {
14891            final XmlSerializer serializer = new FastXmlSerializer();
14892            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14893            serializer.startDocument(null, true);
14894            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14895
14896            synchronized (mPackages) {
14897                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14898            }
14899
14900            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14901            serializer.endDocument();
14902            serializer.flush();
14903        } catch (Exception e) {
14904            if (DEBUG_BACKUP) {
14905                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14906            }
14907            return null;
14908        }
14909
14910        return dataStream.toByteArray();
14911    }
14912
14913    @Override
14914    public void restorePreferredActivities(byte[] backup, int userId) {
14915        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14916            throw new SecurityException("Only the system may call restorePreferredActivities()");
14917        }
14918
14919        try {
14920            final XmlPullParser parser = Xml.newPullParser();
14921            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14922            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14923                    new BlobXmlRestorer() {
14924                        @Override
14925                        public void apply(XmlPullParser parser, int userId)
14926                                throws XmlPullParserException, IOException {
14927                            synchronized (mPackages) {
14928                                mSettings.readPreferredActivitiesLPw(parser, userId);
14929                            }
14930                        }
14931                    } );
14932        } catch (Exception e) {
14933            if (DEBUG_BACKUP) {
14934                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14935            }
14936        }
14937    }
14938
14939    /**
14940     * Non-Binder method, support for the backup/restore mechanism: write the
14941     * default browser (etc) settings in its canonical XML format.  Returns the default
14942     * browser XML representation as a byte array, or null if there is none.
14943     */
14944    @Override
14945    public byte[] getDefaultAppsBackup(int userId) {
14946        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14947            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14948        }
14949
14950        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14951        try {
14952            final XmlSerializer serializer = new FastXmlSerializer();
14953            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14954            serializer.startDocument(null, true);
14955            serializer.startTag(null, TAG_DEFAULT_APPS);
14956
14957            synchronized (mPackages) {
14958                mSettings.writeDefaultAppsLPr(serializer, userId);
14959            }
14960
14961            serializer.endTag(null, TAG_DEFAULT_APPS);
14962            serializer.endDocument();
14963            serializer.flush();
14964        } catch (Exception e) {
14965            if (DEBUG_BACKUP) {
14966                Slog.e(TAG, "Unable to write default apps for backup", e);
14967            }
14968            return null;
14969        }
14970
14971        return dataStream.toByteArray();
14972    }
14973
14974    @Override
14975    public void restoreDefaultApps(byte[] backup, int userId) {
14976        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14977            throw new SecurityException("Only the system may call restoreDefaultApps()");
14978        }
14979
14980        try {
14981            final XmlPullParser parser = Xml.newPullParser();
14982            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14983            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14984                    new BlobXmlRestorer() {
14985                        @Override
14986                        public void apply(XmlPullParser parser, int userId)
14987                                throws XmlPullParserException, IOException {
14988                            synchronized (mPackages) {
14989                                mSettings.readDefaultAppsLPw(parser, userId);
14990                            }
14991                        }
14992                    } );
14993        } catch (Exception e) {
14994            if (DEBUG_BACKUP) {
14995                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14996            }
14997        }
14998    }
14999
15000    @Override
15001    public byte[] getIntentFilterVerificationBackup(int userId) {
15002        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15003            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15004        }
15005
15006        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15007        try {
15008            final XmlSerializer serializer = new FastXmlSerializer();
15009            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15010            serializer.startDocument(null, true);
15011            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15012
15013            synchronized (mPackages) {
15014                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15015            }
15016
15017            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15018            serializer.endDocument();
15019            serializer.flush();
15020        } catch (Exception e) {
15021            if (DEBUG_BACKUP) {
15022                Slog.e(TAG, "Unable to write default apps for backup", e);
15023            }
15024            return null;
15025        }
15026
15027        return dataStream.toByteArray();
15028    }
15029
15030    @Override
15031    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15032        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15033            throw new SecurityException("Only the system may call restorePreferredActivities()");
15034        }
15035
15036        try {
15037            final XmlPullParser parser = Xml.newPullParser();
15038            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15039            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15040                    new BlobXmlRestorer() {
15041                        @Override
15042                        public void apply(XmlPullParser parser, int userId)
15043                                throws XmlPullParserException, IOException {
15044                            synchronized (mPackages) {
15045                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15046                                mSettings.writeLPr();
15047                            }
15048                        }
15049                    } );
15050        } catch (Exception e) {
15051            if (DEBUG_BACKUP) {
15052                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15053            }
15054        }
15055    }
15056
15057    @Override
15058    public byte[] getPermissionGrantBackup(int userId) {
15059        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15060            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15061        }
15062
15063        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15064        try {
15065            final XmlSerializer serializer = new FastXmlSerializer();
15066            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15067            serializer.startDocument(null, true);
15068            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15069
15070            synchronized (mPackages) {
15071                serializeRuntimePermissionGrantsLPr(serializer, userId);
15072            }
15073
15074            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15075            serializer.endDocument();
15076            serializer.flush();
15077        } catch (Exception e) {
15078            if (DEBUG_BACKUP) {
15079                Slog.e(TAG, "Unable to write default apps for backup", e);
15080            }
15081            return null;
15082        }
15083
15084        return dataStream.toByteArray();
15085    }
15086
15087    @Override
15088    public void restorePermissionGrants(byte[] backup, int userId) {
15089        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15090            throw new SecurityException("Only the system may call restorePermissionGrants()");
15091        }
15092
15093        try {
15094            final XmlPullParser parser = Xml.newPullParser();
15095            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15096            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15097                    new BlobXmlRestorer() {
15098                        @Override
15099                        public void apply(XmlPullParser parser, int userId)
15100                                throws XmlPullParserException, IOException {
15101                            synchronized (mPackages) {
15102                                processRestoredPermissionGrantsLPr(parser, userId);
15103                            }
15104                        }
15105                    } );
15106        } catch (Exception e) {
15107            if (DEBUG_BACKUP) {
15108                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15109            }
15110        }
15111    }
15112
15113    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15114            throws IOException {
15115        serializer.startTag(null, TAG_ALL_GRANTS);
15116
15117        final int N = mSettings.mPackages.size();
15118        for (int i = 0; i < N; i++) {
15119            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15120            boolean pkgGrantsKnown = false;
15121
15122            PermissionsState packagePerms = ps.getPermissionsState();
15123
15124            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15125                final int grantFlags = state.getFlags();
15126                // only look at grants that are not system/policy fixed
15127                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15128                    final boolean isGranted = state.isGranted();
15129                    // And only back up the user-twiddled state bits
15130                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15131                        final String packageName = mSettings.mPackages.keyAt(i);
15132                        if (!pkgGrantsKnown) {
15133                            serializer.startTag(null, TAG_GRANT);
15134                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15135                            pkgGrantsKnown = true;
15136                        }
15137
15138                        final boolean userSet =
15139                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15140                        final boolean userFixed =
15141                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15142                        final boolean revoke =
15143                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15144
15145                        serializer.startTag(null, TAG_PERMISSION);
15146                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15147                        if (isGranted) {
15148                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15149                        }
15150                        if (userSet) {
15151                            serializer.attribute(null, ATTR_USER_SET, "true");
15152                        }
15153                        if (userFixed) {
15154                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15155                        }
15156                        if (revoke) {
15157                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15158                        }
15159                        serializer.endTag(null, TAG_PERMISSION);
15160                    }
15161                }
15162            }
15163
15164            if (pkgGrantsKnown) {
15165                serializer.endTag(null, TAG_GRANT);
15166            }
15167        }
15168
15169        serializer.endTag(null, TAG_ALL_GRANTS);
15170    }
15171
15172    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15173            throws XmlPullParserException, IOException {
15174        String pkgName = null;
15175        int outerDepth = parser.getDepth();
15176        int type;
15177        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15178                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15179            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15180                continue;
15181            }
15182
15183            final String tagName = parser.getName();
15184            if (tagName.equals(TAG_GRANT)) {
15185                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15186                if (DEBUG_BACKUP) {
15187                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15188                }
15189            } else if (tagName.equals(TAG_PERMISSION)) {
15190
15191                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15192                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15193
15194                int newFlagSet = 0;
15195                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15196                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15197                }
15198                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15199                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15200                }
15201                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15202                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15203                }
15204                if (DEBUG_BACKUP) {
15205                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15206                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15207                }
15208                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15209                if (ps != null) {
15210                    // Already installed so we apply the grant immediately
15211                    if (DEBUG_BACKUP) {
15212                        Slog.v(TAG, "        + already installed; applying");
15213                    }
15214                    PermissionsState perms = ps.getPermissionsState();
15215                    BasePermission bp = mSettings.mPermissions.get(permName);
15216                    if (bp != null) {
15217                        if (isGranted) {
15218                            perms.grantRuntimePermission(bp, userId);
15219                        }
15220                        if (newFlagSet != 0) {
15221                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15222                        }
15223                    }
15224                } else {
15225                    // Need to wait for post-restore install to apply the grant
15226                    if (DEBUG_BACKUP) {
15227                        Slog.v(TAG, "        - not yet installed; saving for later");
15228                    }
15229                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15230                            isGranted, newFlagSet, userId);
15231                }
15232            } else {
15233                PackageManagerService.reportSettingsProblem(Log.WARN,
15234                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15235                XmlUtils.skipCurrentTag(parser);
15236            }
15237        }
15238
15239        scheduleWriteSettingsLocked();
15240        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15241    }
15242
15243    @Override
15244    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15245            int sourceUserId, int targetUserId, int flags) {
15246        mContext.enforceCallingOrSelfPermission(
15247                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15248        int callingUid = Binder.getCallingUid();
15249        enforceOwnerRights(ownerPackage, callingUid);
15250        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15251        if (intentFilter.countActions() == 0) {
15252            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15253            return;
15254        }
15255        synchronized (mPackages) {
15256            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15257                    ownerPackage, targetUserId, flags);
15258            CrossProfileIntentResolver resolver =
15259                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15260            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15261            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15262            if (existing != null) {
15263                int size = existing.size();
15264                for (int i = 0; i < size; i++) {
15265                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15266                        return;
15267                    }
15268                }
15269            }
15270            resolver.addFilter(newFilter);
15271            scheduleWritePackageRestrictionsLocked(sourceUserId);
15272        }
15273    }
15274
15275    @Override
15276    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15277        mContext.enforceCallingOrSelfPermission(
15278                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15279        int callingUid = Binder.getCallingUid();
15280        enforceOwnerRights(ownerPackage, callingUid);
15281        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15282        synchronized (mPackages) {
15283            CrossProfileIntentResolver resolver =
15284                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15285            ArraySet<CrossProfileIntentFilter> set =
15286                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15287            for (CrossProfileIntentFilter filter : set) {
15288                if (filter.getOwnerPackage().equals(ownerPackage)) {
15289                    resolver.removeFilter(filter);
15290                }
15291            }
15292            scheduleWritePackageRestrictionsLocked(sourceUserId);
15293        }
15294    }
15295
15296    // Enforcing that callingUid is owning pkg on userId
15297    private void enforceOwnerRights(String pkg, int callingUid) {
15298        // The system owns everything.
15299        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15300            return;
15301        }
15302        int callingUserId = UserHandle.getUserId(callingUid);
15303        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15304        if (pi == null) {
15305            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15306                    + callingUserId);
15307        }
15308        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15309            throw new SecurityException("Calling uid " + callingUid
15310                    + " does not own package " + pkg);
15311        }
15312    }
15313
15314    @Override
15315    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15316        Intent intent = new Intent(Intent.ACTION_MAIN);
15317        intent.addCategory(Intent.CATEGORY_HOME);
15318
15319        final int callingUserId = UserHandle.getCallingUserId();
15320        List<ResolveInfo> list = queryIntentActivities(intent, null,
15321                PackageManager.GET_META_DATA, callingUserId);
15322        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15323                true, false, false, callingUserId);
15324
15325        allHomeCandidates.clear();
15326        if (list != null) {
15327            for (ResolveInfo ri : list) {
15328                allHomeCandidates.add(ri);
15329            }
15330        }
15331        return (preferred == null || preferred.activityInfo == null)
15332                ? null
15333                : new ComponentName(preferred.activityInfo.packageName,
15334                        preferred.activityInfo.name);
15335    }
15336
15337    @Override
15338    public void setApplicationEnabledSetting(String appPackageName,
15339            int newState, int flags, int userId, String callingPackage) {
15340        if (!sUserManager.exists(userId)) return;
15341        if (callingPackage == null) {
15342            callingPackage = Integer.toString(Binder.getCallingUid());
15343        }
15344        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15345    }
15346
15347    @Override
15348    public void setComponentEnabledSetting(ComponentName componentName,
15349            int newState, int flags, int userId) {
15350        if (!sUserManager.exists(userId)) return;
15351        setEnabledSetting(componentName.getPackageName(),
15352                componentName.getClassName(), newState, flags, userId, null);
15353    }
15354
15355    private void setEnabledSetting(final String packageName, String className, int newState,
15356            final int flags, int userId, String callingPackage) {
15357        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15358              || newState == COMPONENT_ENABLED_STATE_ENABLED
15359              || newState == COMPONENT_ENABLED_STATE_DISABLED
15360              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15361              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15362            throw new IllegalArgumentException("Invalid new component state: "
15363                    + newState);
15364        }
15365        PackageSetting pkgSetting;
15366        final int uid = Binder.getCallingUid();
15367        final int permission = mContext.checkCallingOrSelfPermission(
15368                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15369        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15370        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15371        boolean sendNow = false;
15372        boolean isApp = (className == null);
15373        String componentName = isApp ? packageName : className;
15374        int packageUid = -1;
15375        ArrayList<String> components;
15376
15377        // writer
15378        synchronized (mPackages) {
15379            pkgSetting = mSettings.mPackages.get(packageName);
15380            if (pkgSetting == null) {
15381                if (className == null) {
15382                    throw new IllegalArgumentException("Unknown package: " + packageName);
15383                }
15384                throw new IllegalArgumentException(
15385                        "Unknown component: " + packageName + "/" + className);
15386            }
15387            // Allow root and verify that userId is not being specified by a different user
15388            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15389                throw new SecurityException(
15390                        "Permission Denial: attempt to change component state from pid="
15391                        + Binder.getCallingPid()
15392                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15393            }
15394            if (className == null) {
15395                // We're dealing with an application/package level state change
15396                if (pkgSetting.getEnabled(userId) == newState) {
15397                    // Nothing to do
15398                    return;
15399                }
15400                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15401                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15402                    // Don't care about who enables an app.
15403                    callingPackage = null;
15404                }
15405                pkgSetting.setEnabled(newState, userId, callingPackage);
15406                // pkgSetting.pkg.mSetEnabled = newState;
15407            } else {
15408                // We're dealing with a component level state change
15409                // First, verify that this is a valid class name.
15410                PackageParser.Package pkg = pkgSetting.pkg;
15411                if (pkg == null || !pkg.hasComponentClassName(className)) {
15412                    if (pkg != null &&
15413                            pkg.applicationInfo.targetSdkVersion >=
15414                                    Build.VERSION_CODES.JELLY_BEAN) {
15415                        throw new IllegalArgumentException("Component class " + className
15416                                + " does not exist in " + packageName);
15417                    } else {
15418                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15419                                + className + " does not exist in " + packageName);
15420                    }
15421                }
15422                switch (newState) {
15423                case COMPONENT_ENABLED_STATE_ENABLED:
15424                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15425                        return;
15426                    }
15427                    break;
15428                case COMPONENT_ENABLED_STATE_DISABLED:
15429                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15430                        return;
15431                    }
15432                    break;
15433                case COMPONENT_ENABLED_STATE_DEFAULT:
15434                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15435                        return;
15436                    }
15437                    break;
15438                default:
15439                    Slog.e(TAG, "Invalid new component state: " + newState);
15440                    return;
15441                }
15442            }
15443            scheduleWritePackageRestrictionsLocked(userId);
15444            components = mPendingBroadcasts.get(userId, packageName);
15445            final boolean newPackage = components == null;
15446            if (newPackage) {
15447                components = new ArrayList<String>();
15448            }
15449            if (!components.contains(componentName)) {
15450                components.add(componentName);
15451            }
15452            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15453                sendNow = true;
15454                // Purge entry from pending broadcast list if another one exists already
15455                // since we are sending one right away.
15456                mPendingBroadcasts.remove(userId, packageName);
15457            } else {
15458                if (newPackage) {
15459                    mPendingBroadcasts.put(userId, packageName, components);
15460                }
15461                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15462                    // Schedule a message
15463                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15464                }
15465            }
15466        }
15467
15468        long callingId = Binder.clearCallingIdentity();
15469        try {
15470            if (sendNow) {
15471                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15472                sendPackageChangedBroadcast(packageName,
15473                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15474            }
15475        } finally {
15476            Binder.restoreCallingIdentity(callingId);
15477        }
15478    }
15479
15480    private void sendPackageChangedBroadcast(String packageName,
15481            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15482        if (DEBUG_INSTALL)
15483            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15484                    + componentNames);
15485        Bundle extras = new Bundle(4);
15486        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15487        String nameList[] = new String[componentNames.size()];
15488        componentNames.toArray(nameList);
15489        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15490        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15491        extras.putInt(Intent.EXTRA_UID, packageUid);
15492        // If this is not reporting a change of the overall package, then only send it
15493        // to registered receivers.  We don't want to launch a swath of apps for every
15494        // little component state change.
15495        final int flags = !componentNames.contains(packageName)
15496                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15497        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15498                new int[] {UserHandle.getUserId(packageUid)});
15499    }
15500
15501    @Override
15502    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15503        if (!sUserManager.exists(userId)) return;
15504        final int uid = Binder.getCallingUid();
15505        final int permission = mContext.checkCallingOrSelfPermission(
15506                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15507        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15508        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15509        // writer
15510        synchronized (mPackages) {
15511            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15512                    allowedByPermission, uid, userId)) {
15513                scheduleWritePackageRestrictionsLocked(userId);
15514            }
15515        }
15516    }
15517
15518    @Override
15519    public String getInstallerPackageName(String packageName) {
15520        // reader
15521        synchronized (mPackages) {
15522            return mSettings.getInstallerPackageNameLPr(packageName);
15523        }
15524    }
15525
15526    @Override
15527    public int getApplicationEnabledSetting(String packageName, int userId) {
15528        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15529        int uid = Binder.getCallingUid();
15530        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15531        // reader
15532        synchronized (mPackages) {
15533            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15534        }
15535    }
15536
15537    @Override
15538    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15539        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15540        int uid = Binder.getCallingUid();
15541        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15542        // reader
15543        synchronized (mPackages) {
15544            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15545        }
15546    }
15547
15548    @Override
15549    public void enterSafeMode() {
15550        enforceSystemOrRoot("Only the system can request entering safe mode");
15551
15552        if (!mSystemReady) {
15553            mSafeMode = true;
15554        }
15555    }
15556
15557    @Override
15558    public void systemReady() {
15559        mSystemReady = true;
15560
15561        // Read the compatibilty setting when the system is ready.
15562        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15563                mContext.getContentResolver(),
15564                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15565        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15566        if (DEBUG_SETTINGS) {
15567            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15568        }
15569
15570        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15571
15572        synchronized (mPackages) {
15573            // Verify that all of the preferred activity components actually
15574            // exist.  It is possible for applications to be updated and at
15575            // that point remove a previously declared activity component that
15576            // had been set as a preferred activity.  We try to clean this up
15577            // the next time we encounter that preferred activity, but it is
15578            // possible for the user flow to never be able to return to that
15579            // situation so here we do a sanity check to make sure we haven't
15580            // left any junk around.
15581            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15582            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15583                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15584                removed.clear();
15585                for (PreferredActivity pa : pir.filterSet()) {
15586                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15587                        removed.add(pa);
15588                    }
15589                }
15590                if (removed.size() > 0) {
15591                    for (int r=0; r<removed.size(); r++) {
15592                        PreferredActivity pa = removed.get(r);
15593                        Slog.w(TAG, "Removing dangling preferred activity: "
15594                                + pa.mPref.mComponent);
15595                        pir.removeFilter(pa);
15596                    }
15597                    mSettings.writePackageRestrictionsLPr(
15598                            mSettings.mPreferredActivities.keyAt(i));
15599                }
15600            }
15601
15602            for (int userId : UserManagerService.getInstance().getUserIds()) {
15603                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15604                    grantPermissionsUserIds = ArrayUtils.appendInt(
15605                            grantPermissionsUserIds, userId);
15606                }
15607            }
15608        }
15609        sUserManager.systemReady();
15610
15611        // If we upgraded grant all default permissions before kicking off.
15612        for (int userId : grantPermissionsUserIds) {
15613            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15614        }
15615
15616        // Kick off any messages waiting for system ready
15617        if (mPostSystemReadyMessages != null) {
15618            for (Message msg : mPostSystemReadyMessages) {
15619                msg.sendToTarget();
15620            }
15621            mPostSystemReadyMessages = null;
15622        }
15623
15624        // Watch for external volumes that come and go over time
15625        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15626        storage.registerListener(mStorageListener);
15627
15628        mInstallerService.systemReady();
15629        mPackageDexOptimizer.systemReady();
15630
15631        MountServiceInternal mountServiceInternal = LocalServices.getService(
15632                MountServiceInternal.class);
15633        mountServiceInternal.addExternalStoragePolicy(
15634                new MountServiceInternal.ExternalStorageMountPolicy() {
15635            @Override
15636            public int getMountMode(int uid, String packageName) {
15637                if (Process.isIsolated(uid)) {
15638                    return Zygote.MOUNT_EXTERNAL_NONE;
15639                }
15640                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15641                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15642                }
15643                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15644                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15645                }
15646                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15647                    return Zygote.MOUNT_EXTERNAL_READ;
15648                }
15649                return Zygote.MOUNT_EXTERNAL_WRITE;
15650            }
15651
15652            @Override
15653            public boolean hasExternalStorage(int uid, String packageName) {
15654                return true;
15655            }
15656        });
15657    }
15658
15659    @Override
15660    public boolean isSafeMode() {
15661        return mSafeMode;
15662    }
15663
15664    @Override
15665    public boolean hasSystemUidErrors() {
15666        return mHasSystemUidErrors;
15667    }
15668
15669    static String arrayToString(int[] array) {
15670        StringBuffer buf = new StringBuffer(128);
15671        buf.append('[');
15672        if (array != null) {
15673            for (int i=0; i<array.length; i++) {
15674                if (i > 0) buf.append(", ");
15675                buf.append(array[i]);
15676            }
15677        }
15678        buf.append(']');
15679        return buf.toString();
15680    }
15681
15682    static class DumpState {
15683        public static final int DUMP_LIBS = 1 << 0;
15684        public static final int DUMP_FEATURES = 1 << 1;
15685        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15686        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15687        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15688        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15689        public static final int DUMP_PERMISSIONS = 1 << 6;
15690        public static final int DUMP_PACKAGES = 1 << 7;
15691        public static final int DUMP_SHARED_USERS = 1 << 8;
15692        public static final int DUMP_MESSAGES = 1 << 9;
15693        public static final int DUMP_PROVIDERS = 1 << 10;
15694        public static final int DUMP_VERIFIERS = 1 << 11;
15695        public static final int DUMP_PREFERRED = 1 << 12;
15696        public static final int DUMP_PREFERRED_XML = 1 << 13;
15697        public static final int DUMP_KEYSETS = 1 << 14;
15698        public static final int DUMP_VERSION = 1 << 15;
15699        public static final int DUMP_INSTALLS = 1 << 16;
15700        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15701        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15702
15703        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15704
15705        private int mTypes;
15706
15707        private int mOptions;
15708
15709        private boolean mTitlePrinted;
15710
15711        private SharedUserSetting mSharedUser;
15712
15713        public boolean isDumping(int type) {
15714            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15715                return true;
15716            }
15717
15718            return (mTypes & type) != 0;
15719        }
15720
15721        public void setDump(int type) {
15722            mTypes |= type;
15723        }
15724
15725        public boolean isOptionEnabled(int option) {
15726            return (mOptions & option) != 0;
15727        }
15728
15729        public void setOptionEnabled(int option) {
15730            mOptions |= option;
15731        }
15732
15733        public boolean onTitlePrinted() {
15734            final boolean printed = mTitlePrinted;
15735            mTitlePrinted = true;
15736            return printed;
15737        }
15738
15739        public boolean getTitlePrinted() {
15740            return mTitlePrinted;
15741        }
15742
15743        public void setTitlePrinted(boolean enabled) {
15744            mTitlePrinted = enabled;
15745        }
15746
15747        public SharedUserSetting getSharedUser() {
15748            return mSharedUser;
15749        }
15750
15751        public void setSharedUser(SharedUserSetting user) {
15752            mSharedUser = user;
15753        }
15754    }
15755
15756    @Override
15757    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15758            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15759        (new PackageManagerShellCommand(this)).exec(
15760                this, in, out, err, args, resultReceiver);
15761    }
15762
15763    @Override
15764    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15765        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15766                != PackageManager.PERMISSION_GRANTED) {
15767            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15768                    + Binder.getCallingPid()
15769                    + ", uid=" + Binder.getCallingUid()
15770                    + " without permission "
15771                    + android.Manifest.permission.DUMP);
15772            return;
15773        }
15774
15775        DumpState dumpState = new DumpState();
15776        boolean fullPreferred = false;
15777        boolean checkin = false;
15778
15779        String packageName = null;
15780        ArraySet<String> permissionNames = null;
15781
15782        int opti = 0;
15783        while (opti < args.length) {
15784            String opt = args[opti];
15785            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15786                break;
15787            }
15788            opti++;
15789
15790            if ("-a".equals(opt)) {
15791                // Right now we only know how to print all.
15792            } else if ("-h".equals(opt)) {
15793                pw.println("Package manager dump options:");
15794                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15795                pw.println("    --checkin: dump for a checkin");
15796                pw.println("    -f: print details of intent filters");
15797                pw.println("    -h: print this help");
15798                pw.println("  cmd may be one of:");
15799                pw.println("    l[ibraries]: list known shared libraries");
15800                pw.println("    f[eatures]: list device features");
15801                pw.println("    k[eysets]: print known keysets");
15802                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15803                pw.println("    perm[issions]: dump permissions");
15804                pw.println("    permission [name ...]: dump declaration and use of given permission");
15805                pw.println("    pref[erred]: print preferred package settings");
15806                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15807                pw.println("    prov[iders]: dump content providers");
15808                pw.println("    p[ackages]: dump installed packages");
15809                pw.println("    s[hared-users]: dump shared user IDs");
15810                pw.println("    m[essages]: print collected runtime messages");
15811                pw.println("    v[erifiers]: print package verifier info");
15812                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15813                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15814                pw.println("    version: print database version info");
15815                pw.println("    write: write current settings now");
15816                pw.println("    installs: details about install sessions");
15817                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15818                pw.println("    <package.name>: info about given package");
15819                return;
15820            } else if ("--checkin".equals(opt)) {
15821                checkin = true;
15822            } else if ("-f".equals(opt)) {
15823                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15824            } else {
15825                pw.println("Unknown argument: " + opt + "; use -h for help");
15826            }
15827        }
15828
15829        // Is the caller requesting to dump a particular piece of data?
15830        if (opti < args.length) {
15831            String cmd = args[opti];
15832            opti++;
15833            // Is this a package name?
15834            if ("android".equals(cmd) || cmd.contains(".")) {
15835                packageName = cmd;
15836                // When dumping a single package, we always dump all of its
15837                // filter information since the amount of data will be reasonable.
15838                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15839            } else if ("check-permission".equals(cmd)) {
15840                if (opti >= args.length) {
15841                    pw.println("Error: check-permission missing permission argument");
15842                    return;
15843                }
15844                String perm = args[opti];
15845                opti++;
15846                if (opti >= args.length) {
15847                    pw.println("Error: check-permission missing package argument");
15848                    return;
15849                }
15850                String pkg = args[opti];
15851                opti++;
15852                int user = UserHandle.getUserId(Binder.getCallingUid());
15853                if (opti < args.length) {
15854                    try {
15855                        user = Integer.parseInt(args[opti]);
15856                    } catch (NumberFormatException e) {
15857                        pw.println("Error: check-permission user argument is not a number: "
15858                                + args[opti]);
15859                        return;
15860                    }
15861                }
15862                pw.println(checkPermission(perm, pkg, user));
15863                return;
15864            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15865                dumpState.setDump(DumpState.DUMP_LIBS);
15866            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15867                dumpState.setDump(DumpState.DUMP_FEATURES);
15868            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15869                if (opti >= args.length) {
15870                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15871                            | DumpState.DUMP_SERVICE_RESOLVERS
15872                            | DumpState.DUMP_RECEIVER_RESOLVERS
15873                            | DumpState.DUMP_CONTENT_RESOLVERS);
15874                } else {
15875                    while (opti < args.length) {
15876                        String name = args[opti];
15877                        if ("a".equals(name) || "activity".equals(name)) {
15878                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15879                        } else if ("s".equals(name) || "service".equals(name)) {
15880                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15881                        } else if ("r".equals(name) || "receiver".equals(name)) {
15882                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15883                        } else if ("c".equals(name) || "content".equals(name)) {
15884                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15885                        } else {
15886                            pw.println("Error: unknown resolver table type: " + name);
15887                            return;
15888                        }
15889                        opti++;
15890                    }
15891                }
15892            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15893                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15894            } else if ("permission".equals(cmd)) {
15895                if (opti >= args.length) {
15896                    pw.println("Error: permission requires permission name");
15897                    return;
15898                }
15899                permissionNames = new ArraySet<>();
15900                while (opti < args.length) {
15901                    permissionNames.add(args[opti]);
15902                    opti++;
15903                }
15904                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15905                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15906            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15907                dumpState.setDump(DumpState.DUMP_PREFERRED);
15908            } else if ("preferred-xml".equals(cmd)) {
15909                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15910                if (opti < args.length && "--full".equals(args[opti])) {
15911                    fullPreferred = true;
15912                    opti++;
15913                }
15914            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15915                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15916            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15917                dumpState.setDump(DumpState.DUMP_PACKAGES);
15918            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15919                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15920            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15921                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15922            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15923                dumpState.setDump(DumpState.DUMP_MESSAGES);
15924            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15925                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15926            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15927                    || "intent-filter-verifiers".equals(cmd)) {
15928                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15929            } else if ("version".equals(cmd)) {
15930                dumpState.setDump(DumpState.DUMP_VERSION);
15931            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15932                dumpState.setDump(DumpState.DUMP_KEYSETS);
15933            } else if ("installs".equals(cmd)) {
15934                dumpState.setDump(DumpState.DUMP_INSTALLS);
15935            } else if ("write".equals(cmd)) {
15936                synchronized (mPackages) {
15937                    mSettings.writeLPr();
15938                    pw.println("Settings written.");
15939                    return;
15940                }
15941            }
15942        }
15943
15944        if (checkin) {
15945            pw.println("vers,1");
15946        }
15947
15948        // reader
15949        synchronized (mPackages) {
15950            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15951                if (!checkin) {
15952                    if (dumpState.onTitlePrinted())
15953                        pw.println();
15954                    pw.println("Database versions:");
15955                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15956                }
15957            }
15958
15959            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15960                if (!checkin) {
15961                    if (dumpState.onTitlePrinted())
15962                        pw.println();
15963                    pw.println("Verifiers:");
15964                    pw.print("  Required: ");
15965                    pw.print(mRequiredVerifierPackage);
15966                    pw.print(" (uid=");
15967                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15968                            UserHandle.USER_SYSTEM));
15969                    pw.println(")");
15970                } else if (mRequiredVerifierPackage != null) {
15971                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15972                    pw.print(",");
15973                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15974                            UserHandle.USER_SYSTEM));
15975                }
15976            }
15977
15978            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15979                    packageName == null) {
15980                if (mIntentFilterVerifierComponent != null) {
15981                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15982                    if (!checkin) {
15983                        if (dumpState.onTitlePrinted())
15984                            pw.println();
15985                        pw.println("Intent Filter Verifier:");
15986                        pw.print("  Using: ");
15987                        pw.print(verifierPackageName);
15988                        pw.print(" (uid=");
15989                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15990                                UserHandle.USER_SYSTEM));
15991                        pw.println(")");
15992                    } else if (verifierPackageName != null) {
15993                        pw.print("ifv,"); pw.print(verifierPackageName);
15994                        pw.print(",");
15995                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15996                                UserHandle.USER_SYSTEM));
15997                    }
15998                } else {
15999                    pw.println();
16000                    pw.println("No Intent Filter Verifier available!");
16001                }
16002            }
16003
16004            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16005                boolean printedHeader = false;
16006                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16007                while (it.hasNext()) {
16008                    String name = it.next();
16009                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16010                    if (!checkin) {
16011                        if (!printedHeader) {
16012                            if (dumpState.onTitlePrinted())
16013                                pw.println();
16014                            pw.println("Libraries:");
16015                            printedHeader = true;
16016                        }
16017                        pw.print("  ");
16018                    } else {
16019                        pw.print("lib,");
16020                    }
16021                    pw.print(name);
16022                    if (!checkin) {
16023                        pw.print(" -> ");
16024                    }
16025                    if (ent.path != null) {
16026                        if (!checkin) {
16027                            pw.print("(jar) ");
16028                            pw.print(ent.path);
16029                        } else {
16030                            pw.print(",jar,");
16031                            pw.print(ent.path);
16032                        }
16033                    } else {
16034                        if (!checkin) {
16035                            pw.print("(apk) ");
16036                            pw.print(ent.apk);
16037                        } else {
16038                            pw.print(",apk,");
16039                            pw.print(ent.apk);
16040                        }
16041                    }
16042                    pw.println();
16043                }
16044            }
16045
16046            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16047                if (dumpState.onTitlePrinted())
16048                    pw.println();
16049                if (!checkin) {
16050                    pw.println("Features:");
16051                }
16052                Iterator<String> it = mAvailableFeatures.keySet().iterator();
16053                while (it.hasNext()) {
16054                    String name = it.next();
16055                    if (!checkin) {
16056                        pw.print("  ");
16057                    } else {
16058                        pw.print("feat,");
16059                    }
16060                    pw.println(name);
16061                }
16062            }
16063
16064            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16065                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16066                        : "Activity Resolver Table:", "  ", packageName,
16067                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16068                    dumpState.setTitlePrinted(true);
16069                }
16070            }
16071            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16072                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16073                        : "Receiver Resolver Table:", "  ", packageName,
16074                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16075                    dumpState.setTitlePrinted(true);
16076                }
16077            }
16078            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16079                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16080                        : "Service Resolver Table:", "  ", packageName,
16081                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16082                    dumpState.setTitlePrinted(true);
16083                }
16084            }
16085            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16086                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16087                        : "Provider Resolver Table:", "  ", packageName,
16088                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16089                    dumpState.setTitlePrinted(true);
16090                }
16091            }
16092
16093            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16094                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16095                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16096                    int user = mSettings.mPreferredActivities.keyAt(i);
16097                    if (pir.dump(pw,
16098                            dumpState.getTitlePrinted()
16099                                ? "\nPreferred Activities User " + user + ":"
16100                                : "Preferred Activities User " + user + ":", "  ",
16101                            packageName, true, false)) {
16102                        dumpState.setTitlePrinted(true);
16103                    }
16104                }
16105            }
16106
16107            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16108                pw.flush();
16109                FileOutputStream fout = new FileOutputStream(fd);
16110                BufferedOutputStream str = new BufferedOutputStream(fout);
16111                XmlSerializer serializer = new FastXmlSerializer();
16112                try {
16113                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16114                    serializer.startDocument(null, true);
16115                    serializer.setFeature(
16116                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16117                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16118                    serializer.endDocument();
16119                    serializer.flush();
16120                } catch (IllegalArgumentException e) {
16121                    pw.println("Failed writing: " + e);
16122                } catch (IllegalStateException e) {
16123                    pw.println("Failed writing: " + e);
16124                } catch (IOException e) {
16125                    pw.println("Failed writing: " + e);
16126                }
16127            }
16128
16129            if (!checkin
16130                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16131                    && packageName == null) {
16132                pw.println();
16133                int count = mSettings.mPackages.size();
16134                if (count == 0) {
16135                    pw.println("No applications!");
16136                    pw.println();
16137                } else {
16138                    final String prefix = "  ";
16139                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16140                    if (allPackageSettings.size() == 0) {
16141                        pw.println("No domain preferred apps!");
16142                        pw.println();
16143                    } else {
16144                        pw.println("App verification status:");
16145                        pw.println();
16146                        count = 0;
16147                        for (PackageSetting ps : allPackageSettings) {
16148                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16149                            if (ivi == null || ivi.getPackageName() == null) continue;
16150                            pw.println(prefix + "Package: " + ivi.getPackageName());
16151                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16152                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16153                            pw.println();
16154                            count++;
16155                        }
16156                        if (count == 0) {
16157                            pw.println(prefix + "No app verification established.");
16158                            pw.println();
16159                        }
16160                        for (int userId : sUserManager.getUserIds()) {
16161                            pw.println("App linkages for user " + userId + ":");
16162                            pw.println();
16163                            count = 0;
16164                            for (PackageSetting ps : allPackageSettings) {
16165                                final long status = ps.getDomainVerificationStatusForUser(userId);
16166                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16167                                    continue;
16168                                }
16169                                pw.println(prefix + "Package: " + ps.name);
16170                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16171                                String statusStr = IntentFilterVerificationInfo.
16172                                        getStatusStringFromValue(status);
16173                                pw.println(prefix + "Status:  " + statusStr);
16174                                pw.println();
16175                                count++;
16176                            }
16177                            if (count == 0) {
16178                                pw.println(prefix + "No configured app linkages.");
16179                                pw.println();
16180                            }
16181                        }
16182                    }
16183                }
16184            }
16185
16186            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16187                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16188                if (packageName == null && permissionNames == null) {
16189                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16190                        if (iperm == 0) {
16191                            if (dumpState.onTitlePrinted())
16192                                pw.println();
16193                            pw.println("AppOp Permissions:");
16194                        }
16195                        pw.print("  AppOp Permission ");
16196                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16197                        pw.println(":");
16198                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16199                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16200                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16201                        }
16202                    }
16203                }
16204            }
16205
16206            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16207                boolean printedSomething = false;
16208                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16209                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16210                        continue;
16211                    }
16212                    if (!printedSomething) {
16213                        if (dumpState.onTitlePrinted())
16214                            pw.println();
16215                        pw.println("Registered ContentProviders:");
16216                        printedSomething = true;
16217                    }
16218                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16219                    pw.print("    "); pw.println(p.toString());
16220                }
16221                printedSomething = false;
16222                for (Map.Entry<String, PackageParser.Provider> entry :
16223                        mProvidersByAuthority.entrySet()) {
16224                    PackageParser.Provider p = entry.getValue();
16225                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16226                        continue;
16227                    }
16228                    if (!printedSomething) {
16229                        if (dumpState.onTitlePrinted())
16230                            pw.println();
16231                        pw.println("ContentProvider Authorities:");
16232                        printedSomething = true;
16233                    }
16234                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16235                    pw.print("    "); pw.println(p.toString());
16236                    if (p.info != null && p.info.applicationInfo != null) {
16237                        final String appInfo = p.info.applicationInfo.toString();
16238                        pw.print("      applicationInfo="); pw.println(appInfo);
16239                    }
16240                }
16241            }
16242
16243            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16244                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16245            }
16246
16247            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16248                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16249            }
16250
16251            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16252                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16253            }
16254
16255            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16256                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16257            }
16258
16259            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16260                // XXX should handle packageName != null by dumping only install data that
16261                // the given package is involved with.
16262                if (dumpState.onTitlePrinted()) pw.println();
16263                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16264            }
16265
16266            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16267                if (dumpState.onTitlePrinted()) pw.println();
16268                mSettings.dumpReadMessagesLPr(pw, dumpState);
16269
16270                pw.println();
16271                pw.println("Package warning messages:");
16272                BufferedReader in = null;
16273                String line = null;
16274                try {
16275                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16276                    while ((line = in.readLine()) != null) {
16277                        if (line.contains("ignored: updated version")) continue;
16278                        pw.println(line);
16279                    }
16280                } catch (IOException ignored) {
16281                } finally {
16282                    IoUtils.closeQuietly(in);
16283                }
16284            }
16285
16286            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16287                BufferedReader in = null;
16288                String line = null;
16289                try {
16290                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16291                    while ((line = in.readLine()) != null) {
16292                        if (line.contains("ignored: updated version")) continue;
16293                        pw.print("msg,");
16294                        pw.println(line);
16295                    }
16296                } catch (IOException ignored) {
16297                } finally {
16298                    IoUtils.closeQuietly(in);
16299                }
16300            }
16301        }
16302    }
16303
16304    private String dumpDomainString(String packageName) {
16305        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16306        List<IntentFilter> filters = getAllIntentFilters(packageName);
16307
16308        ArraySet<String> result = new ArraySet<>();
16309        if (iviList.size() > 0) {
16310            for (IntentFilterVerificationInfo ivi : iviList) {
16311                for (String host : ivi.getDomains()) {
16312                    result.add(host);
16313                }
16314            }
16315        }
16316        if (filters != null && filters.size() > 0) {
16317            for (IntentFilter filter : filters) {
16318                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16319                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16320                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16321                    result.addAll(filter.getHostsList());
16322                }
16323            }
16324        }
16325
16326        StringBuilder sb = new StringBuilder(result.size() * 16);
16327        for (String domain : result) {
16328            if (sb.length() > 0) sb.append(" ");
16329            sb.append(domain);
16330        }
16331        return sb.toString();
16332    }
16333
16334    // ------- apps on sdcard specific code -------
16335    static final boolean DEBUG_SD_INSTALL = false;
16336
16337    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16338
16339    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16340
16341    private boolean mMediaMounted = false;
16342
16343    static String getEncryptKey() {
16344        try {
16345            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16346                    SD_ENCRYPTION_KEYSTORE_NAME);
16347            if (sdEncKey == null) {
16348                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16349                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16350                if (sdEncKey == null) {
16351                    Slog.e(TAG, "Failed to create encryption keys");
16352                    return null;
16353                }
16354            }
16355            return sdEncKey;
16356        } catch (NoSuchAlgorithmException nsae) {
16357            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16358            return null;
16359        } catch (IOException ioe) {
16360            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16361            return null;
16362        }
16363    }
16364
16365    /*
16366     * Update media status on PackageManager.
16367     */
16368    @Override
16369    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16370        int callingUid = Binder.getCallingUid();
16371        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16372            throw new SecurityException("Media status can only be updated by the system");
16373        }
16374        // reader; this apparently protects mMediaMounted, but should probably
16375        // be a different lock in that case.
16376        synchronized (mPackages) {
16377            Log.i(TAG, "Updating external media status from "
16378                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16379                    + (mediaStatus ? "mounted" : "unmounted"));
16380            if (DEBUG_SD_INSTALL)
16381                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16382                        + ", mMediaMounted=" + mMediaMounted);
16383            if (mediaStatus == mMediaMounted) {
16384                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16385                        : 0, -1);
16386                mHandler.sendMessage(msg);
16387                return;
16388            }
16389            mMediaMounted = mediaStatus;
16390        }
16391        // Queue up an async operation since the package installation may take a
16392        // little while.
16393        mHandler.post(new Runnable() {
16394            public void run() {
16395                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16396            }
16397        });
16398    }
16399
16400    /**
16401     * Called by MountService when the initial ASECs to scan are available.
16402     * Should block until all the ASEC containers are finished being scanned.
16403     */
16404    public void scanAvailableAsecs() {
16405        updateExternalMediaStatusInner(true, false, false);
16406        if (mShouldRestoreconData) {
16407            SELinuxMMAC.setRestoreconDone();
16408            mShouldRestoreconData = false;
16409        }
16410    }
16411
16412    /*
16413     * Collect information of applications on external media, map them against
16414     * existing containers and update information based on current mount status.
16415     * Please note that we always have to report status if reportStatus has been
16416     * set to true especially when unloading packages.
16417     */
16418    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16419            boolean externalStorage) {
16420        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16421        int[] uidArr = EmptyArray.INT;
16422
16423        final String[] list = PackageHelper.getSecureContainerList();
16424        if (ArrayUtils.isEmpty(list)) {
16425            Log.i(TAG, "No secure containers found");
16426        } else {
16427            // Process list of secure containers and categorize them
16428            // as active or stale based on their package internal state.
16429
16430            // reader
16431            synchronized (mPackages) {
16432                for (String cid : list) {
16433                    // Leave stages untouched for now; installer service owns them
16434                    if (PackageInstallerService.isStageName(cid)) continue;
16435
16436                    if (DEBUG_SD_INSTALL)
16437                        Log.i(TAG, "Processing container " + cid);
16438                    String pkgName = getAsecPackageName(cid);
16439                    if (pkgName == null) {
16440                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16441                        continue;
16442                    }
16443                    if (DEBUG_SD_INSTALL)
16444                        Log.i(TAG, "Looking for pkg : " + pkgName);
16445
16446                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16447                    if (ps == null) {
16448                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16449                        continue;
16450                    }
16451
16452                    /*
16453                     * Skip packages that are not external if we're unmounting
16454                     * external storage.
16455                     */
16456                    if (externalStorage && !isMounted && !isExternal(ps)) {
16457                        continue;
16458                    }
16459
16460                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16461                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16462                    // The package status is changed only if the code path
16463                    // matches between settings and the container id.
16464                    if (ps.codePathString != null
16465                            && ps.codePathString.startsWith(args.getCodePath())) {
16466                        if (DEBUG_SD_INSTALL) {
16467                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16468                                    + " at code path: " + ps.codePathString);
16469                        }
16470
16471                        // We do have a valid package installed on sdcard
16472                        processCids.put(args, ps.codePathString);
16473                        final int uid = ps.appId;
16474                        if (uid != -1) {
16475                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16476                        }
16477                    } else {
16478                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16479                                + ps.codePathString);
16480                    }
16481                }
16482            }
16483
16484            Arrays.sort(uidArr);
16485        }
16486
16487        // Process packages with valid entries.
16488        if (isMounted) {
16489            if (DEBUG_SD_INSTALL)
16490                Log.i(TAG, "Loading packages");
16491            loadMediaPackages(processCids, uidArr, externalStorage);
16492            startCleaningPackages();
16493            mInstallerService.onSecureContainersAvailable();
16494        } else {
16495            if (DEBUG_SD_INSTALL)
16496                Log.i(TAG, "Unloading packages");
16497            unloadMediaPackages(processCids, uidArr, reportStatus);
16498        }
16499    }
16500
16501    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16502            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16503        final int size = infos.size();
16504        final String[] packageNames = new String[size];
16505        final int[] packageUids = new int[size];
16506        for (int i = 0; i < size; i++) {
16507            final ApplicationInfo info = infos.get(i);
16508            packageNames[i] = info.packageName;
16509            packageUids[i] = info.uid;
16510        }
16511        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16512                finishedReceiver);
16513    }
16514
16515    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16516            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16517        sendResourcesChangedBroadcast(mediaStatus, replacing,
16518                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16519    }
16520
16521    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16522            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16523        int size = pkgList.length;
16524        if (size > 0) {
16525            // Send broadcasts here
16526            Bundle extras = new Bundle();
16527            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16528            if (uidArr != null) {
16529                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16530            }
16531            if (replacing) {
16532                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16533            }
16534            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16535                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16536            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16537        }
16538    }
16539
16540   /*
16541     * Look at potentially valid container ids from processCids If package
16542     * information doesn't match the one on record or package scanning fails,
16543     * the cid is added to list of removeCids. We currently don't delete stale
16544     * containers.
16545     */
16546    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16547            boolean externalStorage) {
16548        ArrayList<String> pkgList = new ArrayList<String>();
16549        Set<AsecInstallArgs> keys = processCids.keySet();
16550
16551        for (AsecInstallArgs args : keys) {
16552            String codePath = processCids.get(args);
16553            if (DEBUG_SD_INSTALL)
16554                Log.i(TAG, "Loading container : " + args.cid);
16555            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16556            try {
16557                // Make sure there are no container errors first.
16558                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16559                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16560                            + " when installing from sdcard");
16561                    continue;
16562                }
16563                // Check code path here.
16564                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16565                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16566                            + " does not match one in settings " + codePath);
16567                    continue;
16568                }
16569                // Parse package
16570                int parseFlags = mDefParseFlags;
16571                if (args.isExternalAsec()) {
16572                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16573                }
16574                if (args.isFwdLocked()) {
16575                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16576                }
16577
16578                synchronized (mInstallLock) {
16579                    PackageParser.Package pkg = null;
16580                    try {
16581                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16582                    } catch (PackageManagerException e) {
16583                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16584                    }
16585                    // Scan the package
16586                    if (pkg != null) {
16587                        /*
16588                         * TODO why is the lock being held? doPostInstall is
16589                         * called in other places without the lock. This needs
16590                         * to be straightened out.
16591                         */
16592                        // writer
16593                        synchronized (mPackages) {
16594                            retCode = PackageManager.INSTALL_SUCCEEDED;
16595                            pkgList.add(pkg.packageName);
16596                            // Post process args
16597                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16598                                    pkg.applicationInfo.uid);
16599                        }
16600                    } else {
16601                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16602                    }
16603                }
16604
16605            } finally {
16606                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16607                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16608                }
16609            }
16610        }
16611        // writer
16612        synchronized (mPackages) {
16613            // If the platform SDK has changed since the last time we booted,
16614            // we need to re-grant app permission to catch any new ones that
16615            // appear. This is really a hack, and means that apps can in some
16616            // cases get permissions that the user didn't initially explicitly
16617            // allow... it would be nice to have some better way to handle
16618            // this situation.
16619            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16620                    : mSettings.getInternalVersion();
16621            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16622                    : StorageManager.UUID_PRIVATE_INTERNAL;
16623
16624            int updateFlags = UPDATE_PERMISSIONS_ALL;
16625            if (ver.sdkVersion != mSdkVersion) {
16626                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16627                        + mSdkVersion + "; regranting permissions for external");
16628                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16629            }
16630            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16631
16632            // Yay, everything is now upgraded
16633            ver.forceCurrent();
16634
16635            // can downgrade to reader
16636            // Persist settings
16637            mSettings.writeLPr();
16638        }
16639        // Send a broadcast to let everyone know we are done processing
16640        if (pkgList.size() > 0) {
16641            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16642        }
16643    }
16644
16645   /*
16646     * Utility method to unload a list of specified containers
16647     */
16648    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16649        // Just unmount all valid containers.
16650        for (AsecInstallArgs arg : cidArgs) {
16651            synchronized (mInstallLock) {
16652                arg.doPostDeleteLI(false);
16653           }
16654       }
16655   }
16656
16657    /*
16658     * Unload packages mounted on external media. This involves deleting package
16659     * data from internal structures, sending broadcasts about diabled packages,
16660     * gc'ing to free up references, unmounting all secure containers
16661     * corresponding to packages on external media, and posting a
16662     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16663     * that we always have to post this message if status has been requested no
16664     * matter what.
16665     */
16666    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16667            final boolean reportStatus) {
16668        if (DEBUG_SD_INSTALL)
16669            Log.i(TAG, "unloading media packages");
16670        ArrayList<String> pkgList = new ArrayList<String>();
16671        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16672        final Set<AsecInstallArgs> keys = processCids.keySet();
16673        for (AsecInstallArgs args : keys) {
16674            String pkgName = args.getPackageName();
16675            if (DEBUG_SD_INSTALL)
16676                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16677            // Delete package internally
16678            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16679            synchronized (mInstallLock) {
16680                boolean res = deletePackageLI(pkgName, null, false, null, null,
16681                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16682                if (res) {
16683                    pkgList.add(pkgName);
16684                } else {
16685                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16686                    failedList.add(args);
16687                }
16688            }
16689        }
16690
16691        // reader
16692        synchronized (mPackages) {
16693            // We didn't update the settings after removing each package;
16694            // write them now for all packages.
16695            mSettings.writeLPr();
16696        }
16697
16698        // We have to absolutely send UPDATED_MEDIA_STATUS only
16699        // after confirming that all the receivers processed the ordered
16700        // broadcast when packages get disabled, force a gc to clean things up.
16701        // and unload all the containers.
16702        if (pkgList.size() > 0) {
16703            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16704                    new IIntentReceiver.Stub() {
16705                public void performReceive(Intent intent, int resultCode, String data,
16706                        Bundle extras, boolean ordered, boolean sticky,
16707                        int sendingUser) throws RemoteException {
16708                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16709                            reportStatus ? 1 : 0, 1, keys);
16710                    mHandler.sendMessage(msg);
16711                }
16712            });
16713        } else {
16714            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16715                    keys);
16716            mHandler.sendMessage(msg);
16717        }
16718    }
16719
16720    private void loadPrivatePackages(final VolumeInfo vol) {
16721        mHandler.post(new Runnable() {
16722            @Override
16723            public void run() {
16724                loadPrivatePackagesInner(vol);
16725            }
16726        });
16727    }
16728
16729    private void loadPrivatePackagesInner(VolumeInfo vol) {
16730        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16731        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16732
16733        final VersionInfo ver;
16734        final List<PackageSetting> packages;
16735        synchronized (mPackages) {
16736            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16737            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16738        }
16739
16740        for (PackageSetting ps : packages) {
16741            synchronized (mInstallLock) {
16742                final PackageParser.Package pkg;
16743                try {
16744                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16745                    loaded.add(pkg.applicationInfo);
16746                } catch (PackageManagerException e) {
16747                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16748                }
16749
16750                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16751                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16752                }
16753            }
16754        }
16755
16756        synchronized (mPackages) {
16757            int updateFlags = UPDATE_PERMISSIONS_ALL;
16758            if (ver.sdkVersion != mSdkVersion) {
16759                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16760                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16761                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16762            }
16763            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16764
16765            // Yay, everything is now upgraded
16766            ver.forceCurrent();
16767
16768            mSettings.writeLPr();
16769        }
16770
16771        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16772        sendResourcesChangedBroadcast(true, false, loaded, null);
16773    }
16774
16775    private void unloadPrivatePackages(final VolumeInfo vol) {
16776        mHandler.post(new Runnable() {
16777            @Override
16778            public void run() {
16779                unloadPrivatePackagesInner(vol);
16780            }
16781        });
16782    }
16783
16784    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16785        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16786        synchronized (mInstallLock) {
16787        synchronized (mPackages) {
16788            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16789            for (PackageSetting ps : packages) {
16790                if (ps.pkg == null) continue;
16791
16792                final ApplicationInfo info = ps.pkg.applicationInfo;
16793                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16794                if (deletePackageLI(ps.name, null, false, null, null,
16795                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16796                    unloaded.add(info);
16797                } else {
16798                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16799                }
16800            }
16801
16802            mSettings.writeLPr();
16803        }
16804        }
16805
16806        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16807        sendResourcesChangedBroadcast(false, false, unloaded, null);
16808    }
16809
16810    /**
16811     * Examine all users present on given mounted volume, and destroy data
16812     * belonging to users that are no longer valid, or whose user ID has been
16813     * recycled.
16814     */
16815    private void reconcileUsers(String volumeUuid) {
16816        final File[] files = FileUtils
16817                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16818        for (File file : files) {
16819            if (!file.isDirectory()) continue;
16820
16821            final int userId;
16822            final UserInfo info;
16823            try {
16824                userId = Integer.parseInt(file.getName());
16825                info = sUserManager.getUserInfo(userId);
16826            } catch (NumberFormatException e) {
16827                Slog.w(TAG, "Invalid user directory " + file);
16828                continue;
16829            }
16830
16831            boolean destroyUser = false;
16832            if (info == null) {
16833                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16834                        + " because no matching user was found");
16835                destroyUser = true;
16836            } else {
16837                try {
16838                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16839                } catch (IOException e) {
16840                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16841                            + " because we failed to enforce serial number: " + e);
16842                    destroyUser = true;
16843                }
16844            }
16845
16846            if (destroyUser) {
16847                synchronized (mInstallLock) {
16848                    try {
16849                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16850                    } catch (InstallerException e) {
16851                        Slog.w(TAG, "Failed to clean up user dirs", e);
16852                    }
16853                }
16854            }
16855        }
16856
16857        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16858        final UserManager um = mContext.getSystemService(UserManager.class);
16859        for (UserInfo user : um.getUsers()) {
16860            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16861            if (userDir.exists()) continue;
16862
16863            try {
16864                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16865                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16866            } catch (IOException e) {
16867                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16868            }
16869        }
16870    }
16871
16872    /**
16873     * Examine all apps present on given mounted volume, and destroy apps that
16874     * aren't expected, either due to uninstallation or reinstallation on
16875     * another volume.
16876     */
16877    private void reconcileApps(String volumeUuid) {
16878        final File[] files = FileUtils
16879                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16880        for (File file : files) {
16881            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16882                    && !PackageInstallerService.isStageName(file.getName());
16883            if (!isPackage) {
16884                // Ignore entries which are not packages
16885                continue;
16886            }
16887
16888            boolean destroyApp = false;
16889            String packageName = null;
16890            try {
16891                final PackageLite pkg = PackageParser.parsePackageLite(file,
16892                        PackageParser.PARSE_MUST_BE_APK);
16893                packageName = pkg.packageName;
16894
16895                synchronized (mPackages) {
16896                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16897                    if (ps == null) {
16898                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16899                                + volumeUuid + " because we found no install record");
16900                        destroyApp = true;
16901                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16902                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16903                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16904                        destroyApp = true;
16905                    }
16906                }
16907
16908            } catch (PackageParserException e) {
16909                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16910                destroyApp = true;
16911            }
16912
16913            if (destroyApp) {
16914                synchronized (mInstallLock) {
16915                    if (packageName != null) {
16916                        removeDataDirsLI(volumeUuid, packageName);
16917                    }
16918                    removeCodePathLI(file);
16919                }
16920            }
16921        }
16922    }
16923
16924    private void unfreezePackage(String packageName) {
16925        synchronized (mPackages) {
16926            final PackageSetting ps = mSettings.mPackages.get(packageName);
16927            if (ps != null) {
16928                ps.frozen = false;
16929            }
16930        }
16931    }
16932
16933    @Override
16934    public int movePackage(final String packageName, final String volumeUuid) {
16935        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16936
16937        final int moveId = mNextMoveId.getAndIncrement();
16938        mHandler.post(new Runnable() {
16939            @Override
16940            public void run() {
16941                try {
16942                    movePackageInternal(packageName, volumeUuid, moveId);
16943                } catch (PackageManagerException e) {
16944                    Slog.w(TAG, "Failed to move " + packageName, e);
16945                    mMoveCallbacks.notifyStatusChanged(moveId,
16946                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16947                }
16948            }
16949        });
16950        return moveId;
16951    }
16952
16953    private void movePackageInternal(final String packageName, final String volumeUuid,
16954            final int moveId) throws PackageManagerException {
16955        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16956        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16957        final PackageManager pm = mContext.getPackageManager();
16958
16959        final boolean currentAsec;
16960        final String currentVolumeUuid;
16961        final File codeFile;
16962        final String installerPackageName;
16963        final String packageAbiOverride;
16964        final int appId;
16965        final String seinfo;
16966        final String label;
16967
16968        // reader
16969        synchronized (mPackages) {
16970            final PackageParser.Package pkg = mPackages.get(packageName);
16971            final PackageSetting ps = mSettings.mPackages.get(packageName);
16972            if (pkg == null || ps == null) {
16973                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16974            }
16975
16976            if (pkg.applicationInfo.isSystemApp()) {
16977                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16978                        "Cannot move system application");
16979            }
16980
16981            if (pkg.applicationInfo.isExternalAsec()) {
16982                currentAsec = true;
16983                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16984            } else if (pkg.applicationInfo.isForwardLocked()) {
16985                currentAsec = true;
16986                currentVolumeUuid = "forward_locked";
16987            } else {
16988                currentAsec = false;
16989                currentVolumeUuid = ps.volumeUuid;
16990
16991                final File probe = new File(pkg.codePath);
16992                final File probeOat = new File(probe, "oat");
16993                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16994                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16995                            "Move only supported for modern cluster style installs");
16996                }
16997            }
16998
16999            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17000                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17001                        "Package already moved to " + volumeUuid);
17002            }
17003
17004            if (ps.frozen) {
17005                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17006                        "Failed to move already frozen package");
17007            }
17008            ps.frozen = true;
17009
17010            codeFile = new File(pkg.codePath);
17011            installerPackageName = ps.installerPackageName;
17012            packageAbiOverride = ps.cpuAbiOverrideString;
17013            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17014            seinfo = pkg.applicationInfo.seinfo;
17015            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17016        }
17017
17018        // Now that we're guarded by frozen state, kill app during move
17019        final long token = Binder.clearCallingIdentity();
17020        try {
17021            killApplication(packageName, appId, "move pkg");
17022        } finally {
17023            Binder.restoreCallingIdentity(token);
17024        }
17025
17026        final Bundle extras = new Bundle();
17027        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17028        extras.putString(Intent.EXTRA_TITLE, label);
17029        mMoveCallbacks.notifyCreated(moveId, extras);
17030
17031        int installFlags;
17032        final boolean moveCompleteApp;
17033        final File measurePath;
17034
17035        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17036            installFlags = INSTALL_INTERNAL;
17037            moveCompleteApp = !currentAsec;
17038            measurePath = Environment.getDataAppDirectory(volumeUuid);
17039        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17040            installFlags = INSTALL_EXTERNAL;
17041            moveCompleteApp = false;
17042            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17043        } else {
17044            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17045            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17046                    || !volume.isMountedWritable()) {
17047                unfreezePackage(packageName);
17048                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17049                        "Move location not mounted private volume");
17050            }
17051
17052            Preconditions.checkState(!currentAsec);
17053
17054            installFlags = INSTALL_INTERNAL;
17055            moveCompleteApp = true;
17056            measurePath = Environment.getDataAppDirectory(volumeUuid);
17057        }
17058
17059        final PackageStats stats = new PackageStats(null, -1);
17060        synchronized (mInstaller) {
17061            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17062                unfreezePackage(packageName);
17063                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17064                        "Failed to measure package size");
17065            }
17066        }
17067
17068        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17069                + stats.dataSize);
17070
17071        final long startFreeBytes = measurePath.getFreeSpace();
17072        final long sizeBytes;
17073        if (moveCompleteApp) {
17074            sizeBytes = stats.codeSize + stats.dataSize;
17075        } else {
17076            sizeBytes = stats.codeSize;
17077        }
17078
17079        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17080            unfreezePackage(packageName);
17081            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17082                    "Not enough free space to move");
17083        }
17084
17085        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17086
17087        final CountDownLatch installedLatch = new CountDownLatch(1);
17088        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17089            @Override
17090            public void onUserActionRequired(Intent intent) throws RemoteException {
17091                throw new IllegalStateException();
17092            }
17093
17094            @Override
17095            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17096                    Bundle extras) throws RemoteException {
17097                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17098                        + PackageManager.installStatusToString(returnCode, msg));
17099
17100                installedLatch.countDown();
17101
17102                // Regardless of success or failure of the move operation,
17103                // always unfreeze the package
17104                unfreezePackage(packageName);
17105
17106                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17107                switch (status) {
17108                    case PackageInstaller.STATUS_SUCCESS:
17109                        mMoveCallbacks.notifyStatusChanged(moveId,
17110                                PackageManager.MOVE_SUCCEEDED);
17111                        break;
17112                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17113                        mMoveCallbacks.notifyStatusChanged(moveId,
17114                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17115                        break;
17116                    default:
17117                        mMoveCallbacks.notifyStatusChanged(moveId,
17118                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17119                        break;
17120                }
17121            }
17122        };
17123
17124        final MoveInfo move;
17125        if (moveCompleteApp) {
17126            // Kick off a thread to report progress estimates
17127            new Thread() {
17128                @Override
17129                public void run() {
17130                    while (true) {
17131                        try {
17132                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17133                                break;
17134                            }
17135                        } catch (InterruptedException ignored) {
17136                        }
17137
17138                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17139                        final int progress = 10 + (int) MathUtils.constrain(
17140                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17141                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17142                    }
17143                }
17144            }.start();
17145
17146            final String dataAppName = codeFile.getName();
17147            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17148                    dataAppName, appId, seinfo);
17149        } else {
17150            move = null;
17151        }
17152
17153        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17154
17155        final Message msg = mHandler.obtainMessage(INIT_COPY);
17156        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17157        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17158                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17159        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17160        msg.obj = params;
17161
17162        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17163                System.identityHashCode(msg.obj));
17164        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17165                System.identityHashCode(msg.obj));
17166
17167        mHandler.sendMessage(msg);
17168    }
17169
17170    @Override
17171    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17172        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17173
17174        final int realMoveId = mNextMoveId.getAndIncrement();
17175        final Bundle extras = new Bundle();
17176        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17177        mMoveCallbacks.notifyCreated(realMoveId, extras);
17178
17179        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17180            @Override
17181            public void onCreated(int moveId, Bundle extras) {
17182                // Ignored
17183            }
17184
17185            @Override
17186            public void onStatusChanged(int moveId, int status, long estMillis) {
17187                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17188            }
17189        };
17190
17191        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17192        storage.setPrimaryStorageUuid(volumeUuid, callback);
17193        return realMoveId;
17194    }
17195
17196    @Override
17197    public int getMoveStatus(int moveId) {
17198        mContext.enforceCallingOrSelfPermission(
17199                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17200        return mMoveCallbacks.mLastStatus.get(moveId);
17201    }
17202
17203    @Override
17204    public void registerMoveCallback(IPackageMoveObserver callback) {
17205        mContext.enforceCallingOrSelfPermission(
17206                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17207        mMoveCallbacks.register(callback);
17208    }
17209
17210    @Override
17211    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17212        mContext.enforceCallingOrSelfPermission(
17213                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17214        mMoveCallbacks.unregister(callback);
17215    }
17216
17217    @Override
17218    public boolean setInstallLocation(int loc) {
17219        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17220                null);
17221        if (getInstallLocation() == loc) {
17222            return true;
17223        }
17224        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17225                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17226            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17227                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17228            return true;
17229        }
17230        return false;
17231   }
17232
17233    @Override
17234    public int getInstallLocation() {
17235        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17236                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17237                PackageHelper.APP_INSTALL_AUTO);
17238    }
17239
17240    /** Called by UserManagerService */
17241    void cleanUpUser(UserManagerService userManager, int userHandle) {
17242        synchronized (mPackages) {
17243            mDirtyUsers.remove(userHandle);
17244            mUserNeedsBadging.delete(userHandle);
17245            mSettings.removeUserLPw(userHandle);
17246            mPendingBroadcasts.remove(userHandle);
17247            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17248        }
17249        synchronized (mInstallLock) {
17250            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17251            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17252                final String volumeUuid = vol.getFsUuid();
17253                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17254                try {
17255                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17256                } catch (InstallerException e) {
17257                    Slog.w(TAG, "Failed to remove user data", e);
17258                }
17259            }
17260            synchronized (mPackages) {
17261                removeUnusedPackagesLILPw(userManager, userHandle);
17262            }
17263        }
17264    }
17265
17266    /**
17267     * We're removing userHandle and would like to remove any downloaded packages
17268     * that are no longer in use by any other user.
17269     * @param userHandle the user being removed
17270     */
17271    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17272        final boolean DEBUG_CLEAN_APKS = false;
17273        int [] users = userManager.getUserIds();
17274        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17275        while (psit.hasNext()) {
17276            PackageSetting ps = psit.next();
17277            if (ps.pkg == null) {
17278                continue;
17279            }
17280            final String packageName = ps.pkg.packageName;
17281            // Skip over if system app
17282            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17283                continue;
17284            }
17285            if (DEBUG_CLEAN_APKS) {
17286                Slog.i(TAG, "Checking package " + packageName);
17287            }
17288            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17289            if (keep) {
17290                if (DEBUG_CLEAN_APKS) {
17291                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17292                }
17293            } else {
17294                for (int i = 0; i < users.length; i++) {
17295                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17296                        keep = true;
17297                        if (DEBUG_CLEAN_APKS) {
17298                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17299                                    + users[i]);
17300                        }
17301                        break;
17302                    }
17303                }
17304            }
17305            if (!keep) {
17306                if (DEBUG_CLEAN_APKS) {
17307                    Slog.i(TAG, "  Removing package " + packageName);
17308                }
17309                mHandler.post(new Runnable() {
17310                    public void run() {
17311                        deletePackageX(packageName, userHandle, 0);
17312                    } //end run
17313                });
17314            }
17315        }
17316    }
17317
17318    /** Called by UserManagerService */
17319    void createNewUser(int userHandle) {
17320        synchronized (mInstallLock) {
17321            try {
17322                mInstaller.createUserConfig(userHandle);
17323            } catch (InstallerException e) {
17324                Slog.w(TAG, "Failed to create user config", e);
17325            }
17326            mSettings.createNewUserLI(this, mInstaller, userHandle);
17327        }
17328        synchronized (mPackages) {
17329            applyFactoryDefaultBrowserLPw(userHandle);
17330            primeDomainVerificationsLPw(userHandle);
17331        }
17332    }
17333
17334    void newUserCreated(final int userHandle) {
17335        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17336        // If permission review for legacy apps is required, we represent
17337        // dagerous permissions for such apps as always granted runtime
17338        // permissions to keep per user flag state whether review is needed.
17339        // Hence, if a new user is added we have to propagate dangerous
17340        // permission grants for these legacy apps.
17341        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17342            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17343                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17344        }
17345    }
17346
17347    @Override
17348    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17349        mContext.enforceCallingOrSelfPermission(
17350                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17351                "Only package verification agents can read the verifier device identity");
17352
17353        synchronized (mPackages) {
17354            return mSettings.getVerifierDeviceIdentityLPw();
17355        }
17356    }
17357
17358    @Override
17359    public void setPermissionEnforced(String permission, boolean enforced) {
17360        // TODO: Now that we no longer change GID for storage, this should to away.
17361        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17362                "setPermissionEnforced");
17363        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17364            synchronized (mPackages) {
17365                if (mSettings.mReadExternalStorageEnforced == null
17366                        || mSettings.mReadExternalStorageEnforced != enforced) {
17367                    mSettings.mReadExternalStorageEnforced = enforced;
17368                    mSettings.writeLPr();
17369                }
17370            }
17371            // kill any non-foreground processes so we restart them and
17372            // grant/revoke the GID.
17373            final IActivityManager am = ActivityManagerNative.getDefault();
17374            if (am != null) {
17375                final long token = Binder.clearCallingIdentity();
17376                try {
17377                    am.killProcessesBelowForeground("setPermissionEnforcement");
17378                } catch (RemoteException e) {
17379                } finally {
17380                    Binder.restoreCallingIdentity(token);
17381                }
17382            }
17383        } else {
17384            throw new IllegalArgumentException("No selective enforcement for " + permission);
17385        }
17386    }
17387
17388    @Override
17389    @Deprecated
17390    public boolean isPermissionEnforced(String permission) {
17391        return true;
17392    }
17393
17394    @Override
17395    public boolean isStorageLow() {
17396        final long token = Binder.clearCallingIdentity();
17397        try {
17398            final DeviceStorageMonitorInternal
17399                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17400            if (dsm != null) {
17401                return dsm.isMemoryLow();
17402            } else {
17403                return false;
17404            }
17405        } finally {
17406            Binder.restoreCallingIdentity(token);
17407        }
17408    }
17409
17410    @Override
17411    public IPackageInstaller getPackageInstaller() {
17412        return mInstallerService;
17413    }
17414
17415    private boolean userNeedsBadging(int userId) {
17416        int index = mUserNeedsBadging.indexOfKey(userId);
17417        if (index < 0) {
17418            final UserInfo userInfo;
17419            final long token = Binder.clearCallingIdentity();
17420            try {
17421                userInfo = sUserManager.getUserInfo(userId);
17422            } finally {
17423                Binder.restoreCallingIdentity(token);
17424            }
17425            final boolean b;
17426            if (userInfo != null && userInfo.isManagedProfile()) {
17427                b = true;
17428            } else {
17429                b = false;
17430            }
17431            mUserNeedsBadging.put(userId, b);
17432            return b;
17433        }
17434        return mUserNeedsBadging.valueAt(index);
17435    }
17436
17437    @Override
17438    public KeySet getKeySetByAlias(String packageName, String alias) {
17439        if (packageName == null || alias == null) {
17440            return null;
17441        }
17442        synchronized(mPackages) {
17443            final PackageParser.Package pkg = mPackages.get(packageName);
17444            if (pkg == null) {
17445                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17446                throw new IllegalArgumentException("Unknown package: " + packageName);
17447            }
17448            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17449            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17450        }
17451    }
17452
17453    @Override
17454    public KeySet getSigningKeySet(String packageName) {
17455        if (packageName == null) {
17456            return null;
17457        }
17458        synchronized(mPackages) {
17459            final PackageParser.Package pkg = mPackages.get(packageName);
17460            if (pkg == null) {
17461                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17462                throw new IllegalArgumentException("Unknown package: " + packageName);
17463            }
17464            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17465                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17466                throw new SecurityException("May not access signing KeySet of other apps.");
17467            }
17468            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17469            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17470        }
17471    }
17472
17473    @Override
17474    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17475        if (packageName == null || ks == null) {
17476            return false;
17477        }
17478        synchronized(mPackages) {
17479            final PackageParser.Package pkg = mPackages.get(packageName);
17480            if (pkg == null) {
17481                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17482                throw new IllegalArgumentException("Unknown package: " + packageName);
17483            }
17484            IBinder ksh = ks.getToken();
17485            if (ksh instanceof KeySetHandle) {
17486                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17487                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17488            }
17489            return false;
17490        }
17491    }
17492
17493    @Override
17494    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17495        if (packageName == null || ks == null) {
17496            return false;
17497        }
17498        synchronized(mPackages) {
17499            final PackageParser.Package pkg = mPackages.get(packageName);
17500            if (pkg == null) {
17501                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17502                throw new IllegalArgumentException("Unknown package: " + packageName);
17503            }
17504            IBinder ksh = ks.getToken();
17505            if (ksh instanceof KeySetHandle) {
17506                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17507                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17508            }
17509            return false;
17510        }
17511    }
17512
17513    private void deletePackageIfUnusedLPr(final String packageName) {
17514        PackageSetting ps = mSettings.mPackages.get(packageName);
17515        if (ps == null) {
17516            return;
17517        }
17518        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17519            // TODO Implement atomic delete if package is unused
17520            // It is currently possible that the package will be deleted even if it is installed
17521            // after this method returns.
17522            mHandler.post(new Runnable() {
17523                public void run() {
17524                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17525                }
17526            });
17527        }
17528    }
17529
17530    /**
17531     * Check and throw if the given before/after packages would be considered a
17532     * downgrade.
17533     */
17534    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17535            throws PackageManagerException {
17536        if (after.versionCode < before.mVersionCode) {
17537            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17538                    "Update version code " + after.versionCode + " is older than current "
17539                    + before.mVersionCode);
17540        } else if (after.versionCode == before.mVersionCode) {
17541            if (after.baseRevisionCode < before.baseRevisionCode) {
17542                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17543                        "Update base revision code " + after.baseRevisionCode
17544                        + " is older than current " + before.baseRevisionCode);
17545            }
17546
17547            if (!ArrayUtils.isEmpty(after.splitNames)) {
17548                for (int i = 0; i < after.splitNames.length; i++) {
17549                    final String splitName = after.splitNames[i];
17550                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17551                    if (j != -1) {
17552                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17553                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17554                                    "Update split " + splitName + " revision code "
17555                                    + after.splitRevisionCodes[i] + " is older than current "
17556                                    + before.splitRevisionCodes[j]);
17557                        }
17558                    }
17559                }
17560            }
17561        }
17562    }
17563
17564    private static class MoveCallbacks extends Handler {
17565        private static final int MSG_CREATED = 1;
17566        private static final int MSG_STATUS_CHANGED = 2;
17567
17568        private final RemoteCallbackList<IPackageMoveObserver>
17569                mCallbacks = new RemoteCallbackList<>();
17570
17571        private final SparseIntArray mLastStatus = new SparseIntArray();
17572
17573        public MoveCallbacks(Looper looper) {
17574            super(looper);
17575        }
17576
17577        public void register(IPackageMoveObserver callback) {
17578            mCallbacks.register(callback);
17579        }
17580
17581        public void unregister(IPackageMoveObserver callback) {
17582            mCallbacks.unregister(callback);
17583        }
17584
17585        @Override
17586        public void handleMessage(Message msg) {
17587            final SomeArgs args = (SomeArgs) msg.obj;
17588            final int n = mCallbacks.beginBroadcast();
17589            for (int i = 0; i < n; i++) {
17590                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17591                try {
17592                    invokeCallback(callback, msg.what, args);
17593                } catch (RemoteException ignored) {
17594                }
17595            }
17596            mCallbacks.finishBroadcast();
17597            args.recycle();
17598        }
17599
17600        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17601                throws RemoteException {
17602            switch (what) {
17603                case MSG_CREATED: {
17604                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17605                    break;
17606                }
17607                case MSG_STATUS_CHANGED: {
17608                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17609                    break;
17610                }
17611            }
17612        }
17613
17614        private void notifyCreated(int moveId, Bundle extras) {
17615            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17616
17617            final SomeArgs args = SomeArgs.obtain();
17618            args.argi1 = moveId;
17619            args.arg2 = extras;
17620            obtainMessage(MSG_CREATED, args).sendToTarget();
17621        }
17622
17623        private void notifyStatusChanged(int moveId, int status) {
17624            notifyStatusChanged(moveId, status, -1);
17625        }
17626
17627        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17628            Slog.v(TAG, "Move " + moveId + " status " + status);
17629
17630            final SomeArgs args = SomeArgs.obtain();
17631            args.argi1 = moveId;
17632            args.argi2 = status;
17633            args.arg3 = estMillis;
17634            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17635
17636            synchronized (mLastStatus) {
17637                mLastStatus.put(moveId, status);
17638            }
17639        }
17640    }
17641
17642    private final static class OnPermissionChangeListeners extends Handler {
17643        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17644
17645        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17646                new RemoteCallbackList<>();
17647
17648        public OnPermissionChangeListeners(Looper looper) {
17649            super(looper);
17650        }
17651
17652        @Override
17653        public void handleMessage(Message msg) {
17654            switch (msg.what) {
17655                case MSG_ON_PERMISSIONS_CHANGED: {
17656                    final int uid = msg.arg1;
17657                    handleOnPermissionsChanged(uid);
17658                } break;
17659            }
17660        }
17661
17662        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17663            mPermissionListeners.register(listener);
17664
17665        }
17666
17667        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17668            mPermissionListeners.unregister(listener);
17669        }
17670
17671        public void onPermissionsChanged(int uid) {
17672            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17673                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17674            }
17675        }
17676
17677        private void handleOnPermissionsChanged(int uid) {
17678            final int count = mPermissionListeners.beginBroadcast();
17679            try {
17680                for (int i = 0; i < count; i++) {
17681                    IOnPermissionsChangeListener callback = mPermissionListeners
17682                            .getBroadcastItem(i);
17683                    try {
17684                        callback.onPermissionsChanged(uid);
17685                    } catch (RemoteException e) {
17686                        Log.e(TAG, "Permission listener is dead", e);
17687                    }
17688                }
17689            } finally {
17690                mPermissionListeners.finishBroadcast();
17691            }
17692        }
17693    }
17694
17695    private class PackageManagerInternalImpl extends PackageManagerInternal {
17696        @Override
17697        public void setLocationPackagesProvider(PackagesProvider provider) {
17698            synchronized (mPackages) {
17699                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17700            }
17701        }
17702
17703        @Override
17704        public void setImePackagesProvider(PackagesProvider provider) {
17705            synchronized (mPackages) {
17706                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17707            }
17708        }
17709
17710        @Override
17711        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17712            synchronized (mPackages) {
17713                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17714            }
17715        }
17716
17717        @Override
17718        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17719            synchronized (mPackages) {
17720                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17721            }
17722        }
17723
17724        @Override
17725        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17726            synchronized (mPackages) {
17727                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17728            }
17729        }
17730
17731        @Override
17732        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17733            synchronized (mPackages) {
17734                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17735            }
17736        }
17737
17738        @Override
17739        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17740            synchronized (mPackages) {
17741                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17742            }
17743        }
17744
17745        @Override
17746        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17747            synchronized (mPackages) {
17748                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17749                        packageName, userId);
17750            }
17751        }
17752
17753        @Override
17754        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17755            synchronized (mPackages) {
17756                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17757                        packageName, userId);
17758            }
17759        }
17760
17761        @Override
17762        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17763            synchronized (mPackages) {
17764                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17765                        packageName, userId);
17766            }
17767        }
17768
17769        @Override
17770        public void setKeepUninstalledPackages(final List<String> packageList) {
17771            Preconditions.checkNotNull(packageList);
17772            List<String> removedFromList = null;
17773            synchronized (mPackages) {
17774                if (mKeepUninstalledPackages != null) {
17775                    final int packagesCount = mKeepUninstalledPackages.size();
17776                    for (int i = 0; i < packagesCount; i++) {
17777                        String oldPackage = mKeepUninstalledPackages.get(i);
17778                        if (packageList != null && packageList.contains(oldPackage)) {
17779                            continue;
17780                        }
17781                        if (removedFromList == null) {
17782                            removedFromList = new ArrayList<>();
17783                        }
17784                        removedFromList.add(oldPackage);
17785                    }
17786                }
17787                mKeepUninstalledPackages = new ArrayList<>(packageList);
17788                if (removedFromList != null) {
17789                    final int removedCount = removedFromList.size();
17790                    for (int i = 0; i < removedCount; i++) {
17791                        deletePackageIfUnusedLPr(removedFromList.get(i));
17792                    }
17793                }
17794            }
17795        }
17796
17797        @Override
17798        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17799            synchronized (mPackages) {
17800                // If we do not support permission review, done.
17801                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17802                    return false;
17803                }
17804
17805                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17806                if (packageSetting == null) {
17807                    return false;
17808                }
17809
17810                // Permission review applies only to apps not supporting the new permission model.
17811                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17812                    return false;
17813                }
17814
17815                // Legacy apps have the permission and get user consent on launch.
17816                PermissionsState permissionsState = packageSetting.getPermissionsState();
17817                return permissionsState.isPermissionReviewRequired(userId);
17818            }
17819        }
17820    }
17821
17822    @Override
17823    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17824        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17825        synchronized (mPackages) {
17826            final long identity = Binder.clearCallingIdentity();
17827            try {
17828                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17829                        packageNames, userId);
17830            } finally {
17831                Binder.restoreCallingIdentity(identity);
17832            }
17833        }
17834    }
17835
17836    private static void enforceSystemOrPhoneCaller(String tag) {
17837        int callingUid = Binder.getCallingUid();
17838        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17839            throw new SecurityException(
17840                    "Cannot call " + tag + " from UID " + callingUid);
17841        }
17842    }
17843}
17844