PackageManagerService.java revision fc41ea320f203afa182c7f5816b2ae8072132dd1
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.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Process.PACKAGE_INFO_GID;
79import static android.os.Process.SYSTEM_UID;
80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
81import static android.system.OsConstants.O_CREAT;
82import static android.system.OsConstants.O_RDWR;
83
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
88import static com.android.internal.util.ArrayUtils.appendInt;
89import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100
101import android.Manifest;
102import android.annotation.NonNull;
103import android.annotation.Nullable;
104import android.app.ActivityManager;
105import android.app.ActivityManagerNative;
106import android.app.IActivityManager;
107import android.app.admin.DevicePolicyManagerInternal;
108import android.app.admin.IDevicePolicyManager;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralResolveInfo;
125import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
126import android.content.pm.FeatureInfo;
127import android.content.pm.IOnPermissionsChangeListener;
128import android.content.pm.IPackageDataObserver;
129import android.content.pm.IPackageDeleteObserver;
130import android.content.pm.IPackageDeleteObserver2;
131import android.content.pm.IPackageInstallObserver2;
132import android.content.pm.IPackageInstaller;
133import android.content.pm.IPackageManager;
134import android.content.pm.IPackageMoveObserver;
135import android.content.pm.IPackageStatsObserver;
136import android.content.pm.InstrumentationInfo;
137import android.content.pm.IntentFilterVerificationInfo;
138import android.content.pm.KeySet;
139import android.content.pm.PackageCleanItem;
140import android.content.pm.PackageInfo;
141import android.content.pm.PackageInfoLite;
142import android.content.pm.PackageInstaller;
143import android.content.pm.PackageManager;
144import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
145import android.content.pm.PackageManagerInternal;
146import android.content.pm.PackageParser;
147import android.content.pm.PackageParser.ActivityIntentInfo;
148import android.content.pm.PackageParser.PackageLite;
149import android.content.pm.PackageParser.PackageParserException;
150import android.content.pm.PackageStats;
151import android.content.pm.PackageUserState;
152import android.content.pm.ParceledListSlice;
153import android.content.pm.PermissionGroupInfo;
154import android.content.pm.PermissionInfo;
155import android.content.pm.ProviderInfo;
156import android.content.pm.ResolveInfo;
157import android.content.pm.ServiceInfo;
158import android.content.pm.Signature;
159import android.content.pm.UserInfo;
160import android.content.pm.VerifierDeviceIdentity;
161import android.content.pm.VerifierInfo;
162import android.content.res.Resources;
163import android.graphics.Bitmap;
164import android.hardware.display.DisplayManager;
165import android.net.Uri;
166import android.os.Binder;
167import android.os.Build;
168import android.os.Bundle;
169import android.os.Debug;
170import android.os.Environment;
171import android.os.Environment.UserEnvironment;
172import android.os.FileUtils;
173import android.os.Handler;
174import android.os.IBinder;
175import android.os.Looper;
176import android.os.Message;
177import android.os.Parcel;
178import android.os.ParcelFileDescriptor;
179import android.os.Process;
180import android.os.RemoteCallbackList;
181import android.os.RemoteException;
182import android.os.ResultReceiver;
183import android.os.SELinux;
184import android.os.ServiceManager;
185import android.os.SystemClock;
186import android.os.SystemProperties;
187import android.os.Trace;
188import android.os.UserHandle;
189import android.os.UserManager;
190import android.os.storage.IMountService;
191import android.os.storage.MountServiceInternal;
192import android.os.storage.StorageEventListener;
193import android.os.storage.StorageManager;
194import android.os.storage.VolumeInfo;
195import android.os.storage.VolumeRecord;
196import android.security.KeyStore;
197import android.security.SystemKeyStore;
198import android.system.ErrnoException;
199import android.system.Os;
200import android.text.TextUtils;
201import android.text.format.DateUtils;
202import android.util.ArrayMap;
203import android.util.ArraySet;
204import android.util.AtomicFile;
205import android.util.DisplayMetrics;
206import android.util.EventLog;
207import android.util.ExceptionUtils;
208import android.util.Log;
209import android.util.LogPrinter;
210import android.util.MathUtils;
211import android.util.PrintStreamPrinter;
212import android.util.Slog;
213import android.util.SparseArray;
214import android.util.SparseBooleanArray;
215import android.util.SparseIntArray;
216import android.util.Xml;
217import android.view.Display;
218
219import com.android.internal.R;
220import com.android.internal.annotations.GuardedBy;
221import com.android.internal.app.IMediaContainerService;
222import com.android.internal.app.ResolverActivity;
223import com.android.internal.content.NativeLibraryHelper;
224import com.android.internal.content.PackageHelper;
225import com.android.internal.os.IParcelFileDescriptorFactory;
226import com.android.internal.os.InstallerConnection.InstallerException;
227import com.android.internal.os.SomeArgs;
228import com.android.internal.os.Zygote;
229import com.android.internal.util.ArrayUtils;
230import com.android.internal.util.FastPrintWriter;
231import com.android.internal.util.FastXmlSerializer;
232import com.android.internal.util.IndentingPrintWriter;
233import com.android.internal.util.Preconditions;
234import com.android.internal.util.XmlUtils;
235import com.android.server.EventLogTags;
236import com.android.server.FgThread;
237import com.android.server.IntentResolver;
238import com.android.server.LocalServices;
239import com.android.server.ServiceThread;
240import com.android.server.SystemConfig;
241import com.android.server.Watchdog;
242import com.android.server.pm.PermissionsState.PermissionState;
243import com.android.server.pm.Settings.DatabaseVersion;
244import com.android.server.pm.Settings.VersionInfo;
245import com.android.server.storage.DeviceStorageMonitorInternal;
246
247import dalvik.system.DexFile;
248import dalvik.system.VMRuntime;
249
250import libcore.io.IoUtils;
251import libcore.util.EmptyArray;
252
253import org.xmlpull.v1.XmlPullParser;
254import org.xmlpull.v1.XmlPullParserException;
255import org.xmlpull.v1.XmlSerializer;
256
257import java.io.BufferedInputStream;
258import java.io.BufferedOutputStream;
259import java.io.BufferedReader;
260import java.io.ByteArrayInputStream;
261import java.io.ByteArrayOutputStream;
262import java.io.File;
263import java.io.FileDescriptor;
264import java.io.FileNotFoundException;
265import java.io.FileOutputStream;
266import java.io.FileReader;
267import java.io.FilenameFilter;
268import java.io.IOException;
269import java.io.InputStream;
270import java.io.PrintWriter;
271import java.nio.charset.StandardCharsets;
272import java.security.MessageDigest;
273import java.security.NoSuchAlgorithmException;
274import java.security.PublicKey;
275import java.security.cert.CertificateEncodingException;
276import java.security.cert.CertificateException;
277import java.text.SimpleDateFormat;
278import java.util.ArrayList;
279import java.util.Arrays;
280import java.util.Collection;
281import java.util.Collections;
282import java.util.Comparator;
283import java.util.Date;
284import java.util.HashSet;
285import java.util.Iterator;
286import java.util.List;
287import java.util.Map;
288import java.util.Objects;
289import java.util.Set;
290import java.util.concurrent.CountDownLatch;
291import java.util.concurrent.TimeUnit;
292import java.util.concurrent.atomic.AtomicBoolean;
293import java.util.concurrent.atomic.AtomicInteger;
294import java.util.concurrent.atomic.AtomicLong;
295
296/**
297 * Keep track of all those .apks everywhere.
298 *
299 * This is very central to the platform's security; please run the unit
300 * tests whenever making modifications here:
301 *
302runtest -c android.content.pm.PackageManagerTests frameworks-core
303 *
304 * {@hide}
305 */
306public class PackageManagerService extends IPackageManager.Stub {
307    static final String TAG = "PackageManager";
308    static final boolean DEBUG_SETTINGS = false;
309    static final boolean DEBUG_PREFERRED = false;
310    static final boolean DEBUG_UPGRADE = false;
311    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
312    private static final boolean DEBUG_BACKUP = false;
313    private static final boolean DEBUG_INSTALL = false;
314    private static final boolean DEBUG_REMOVE = false;
315    private static final boolean DEBUG_BROADCASTS = false;
316    private static final boolean DEBUG_SHOW_INFO = false;
317    private static final boolean DEBUG_PACKAGE_INFO = false;
318    private static final boolean DEBUG_INTENT_MATCHING = false;
319    private static final boolean DEBUG_PACKAGE_SCANNING = false;
320    private static final boolean DEBUG_VERIFY = false;
321
322    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
323    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
324    // user, but by default initialize to this.
325    static final boolean DEBUG_DEXOPT = false;
326
327    private static final boolean DEBUG_ABI_SELECTION = false;
328    private static final boolean DEBUG_EPHEMERAL = false;
329    private static final boolean DEBUG_TRIAGED_MISSING = false;
330    private static final boolean DEBUG_APP_DATA = false;
331
332    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
333
334    private static final boolean DISABLE_EPHEMERAL_APPS = true;
335
336    private static final int RADIO_UID = Process.PHONE_UID;
337    private static final int LOG_UID = Process.LOG_UID;
338    private static final int NFC_UID = Process.NFC_UID;
339    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
340    private static final int SHELL_UID = Process.SHELL_UID;
341
342    // Cap the size of permission trees that 3rd party apps can define
343    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
344
345    // Suffix used during package installation when copying/moving
346    // package apks to install directory.
347    private static final String INSTALL_PACKAGE_SUFFIX = "-";
348
349    static final int SCAN_NO_DEX = 1<<1;
350    static final int SCAN_FORCE_DEX = 1<<2;
351    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
352    static final int SCAN_NEW_INSTALL = 1<<4;
353    static final int SCAN_NO_PATHS = 1<<5;
354    static final int SCAN_UPDATE_TIME = 1<<6;
355    static final int SCAN_DEFER_DEX = 1<<7;
356    static final int SCAN_BOOTING = 1<<8;
357    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
358    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
359    static final int SCAN_REPLACING = 1<<11;
360    static final int SCAN_REQUIRE_KNOWN = 1<<12;
361    static final int SCAN_MOVE = 1<<13;
362    static final int SCAN_INITIAL = 1<<14;
363    static final int SCAN_CHECK_ONLY = 1<<15;
364    static final int SCAN_DONT_KILL_APP = 1<<17;
365
366    static final int REMOVE_CHATTY = 1<<16;
367
368    private static final int[] EMPTY_INT_ARRAY = new int[0];
369
370    /**
371     * Timeout (in milliseconds) after which the watchdog should declare that
372     * our handler thread is wedged.  The usual default for such things is one
373     * minute but we sometimes do very lengthy I/O operations on this thread,
374     * such as installing multi-gigabyte applications, so ours needs to be longer.
375     */
376    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
377
378    /**
379     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
380     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
381     * settings entry if available, otherwise we use the hardcoded default.  If it's been
382     * more than this long since the last fstrim, we force one during the boot sequence.
383     *
384     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
385     * one gets run at the next available charging+idle time.  This final mandatory
386     * no-fstrim check kicks in only of the other scheduling criteria is never met.
387     */
388    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
389
390    /**
391     * Whether verification is enabled by default.
392     */
393    private static final boolean DEFAULT_VERIFY_ENABLE = true;
394
395    /**
396     * The default maximum time to wait for the verification agent to return in
397     * milliseconds.
398     */
399    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
400
401    /**
402     * The default response for package verification timeout.
403     *
404     * This can be either PackageManager.VERIFICATION_ALLOW or
405     * PackageManager.VERIFICATION_REJECT.
406     */
407    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
408
409    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
410
411    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
412            DEFAULT_CONTAINER_PACKAGE,
413            "com.android.defcontainer.DefaultContainerService");
414
415    private static final String KILL_APP_REASON_GIDS_CHANGED =
416            "permission grant or revoke changed gids";
417
418    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
419            "permissions revoked";
420
421    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
422
423    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
424
425    /** Permission grant: not grant the permission. */
426    private static final int GRANT_DENIED = 1;
427
428    /** Permission grant: grant the permission as an install permission. */
429    private static final int GRANT_INSTALL = 2;
430
431    /** Permission grant: grant the permission as a runtime one. */
432    private static final int GRANT_RUNTIME = 3;
433
434    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
435    private static final int GRANT_UPGRADE = 4;
436
437    /** Canonical intent used to identify what counts as a "web browser" app */
438    private static final Intent sBrowserIntent;
439    static {
440        sBrowserIntent = new Intent();
441        sBrowserIntent.setAction(Intent.ACTION_VIEW);
442        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
443        sBrowserIntent.setData(Uri.parse("http:"));
444    }
445
446    // Compilation reasons.
447    public static final int REASON_FIRST_BOOT = 0;
448    public static final int REASON_BOOT = 1;
449    public static final int REASON_INSTALL = 2;
450    public static final int REASON_BACKGROUND_DEXOPT = 3;
451    public static final int REASON_AB_OTA = 4;
452    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
453    public static final int REASON_SHARED_APK = 6;
454    public static final int REASON_FORCED_DEXOPT = 7;
455
456    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
457
458    final ServiceThread mHandlerThread;
459
460    final PackageHandler mHandler;
461
462    /**
463     * Messages for {@link #mHandler} that need to wait for system ready before
464     * being dispatched.
465     */
466    private ArrayList<Message> mPostSystemReadyMessages;
467
468    final int mSdkVersion = Build.VERSION.SDK_INT;
469
470    final Context mContext;
471    final boolean mFactoryTest;
472    final boolean mOnlyCore;
473    final DisplayMetrics mMetrics;
474    final int mDefParseFlags;
475    final String[] mSeparateProcesses;
476    final boolean mIsUpgrade;
477    final boolean mIsPreNUpgrade;
478
479    /** The location for ASEC container files on internal storage. */
480    final String mAsecInternalPath;
481
482    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
483    // LOCK HELD.  Can be called with mInstallLock held.
484    @GuardedBy("mInstallLock")
485    final Installer mInstaller;
486
487    /** Directory where installed third-party apps stored */
488    final File mAppInstallDir;
489    final File mEphemeralInstallDir;
490
491    /**
492     * Directory to which applications installed internally have their
493     * 32 bit native libraries copied.
494     */
495    private File mAppLib32InstallDir;
496
497    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
498    // apps.
499    final File mDrmAppPrivateInstallDir;
500
501    // ----------------------------------------------------------------
502
503    // Lock for state used when installing and doing other long running
504    // operations.  Methods that must be called with this lock held have
505    // the suffix "LI".
506    final Object mInstallLock = new Object();
507
508    // ----------------------------------------------------------------
509
510    // Keys are String (package name), values are Package.  This also serves
511    // as the lock for the global state.  Methods that must be called with
512    // this lock held have the prefix "LP".
513    @GuardedBy("mPackages")
514    final ArrayMap<String, PackageParser.Package> mPackages =
515            new ArrayMap<String, PackageParser.Package>();
516
517    final ArrayMap<String, Set<String>> mKnownCodebase =
518            new ArrayMap<String, Set<String>>();
519
520    // Tracks available target package names -> overlay package paths.
521    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
522        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
523
524    /**
525     * Tracks new system packages [received in an OTA] that we expect to
526     * find updated user-installed versions. Keys are package name, values
527     * are package location.
528     */
529    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
530
531    /**
532     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
533     */
534    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
535    /**
536     * Whether or not system app permissions should be promoted from install to runtime.
537     */
538    boolean mPromoteSystemApps;
539
540    final Settings mSettings;
541    boolean mRestoredSettings;
542
543    // System configuration read by SystemConfig.
544    final int[] mGlobalGids;
545    final SparseArray<ArraySet<String>> mSystemPermissions;
546    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
547
548    // If mac_permissions.xml was found for seinfo labeling.
549    boolean mFoundPolicyFile;
550
551    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
552
553    public static final class SharedLibraryEntry {
554        public final String path;
555        public final String apk;
556
557        SharedLibraryEntry(String _path, String _apk) {
558            path = _path;
559            apk = _apk;
560        }
561    }
562
563    // Currently known shared libraries.
564    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
565            new ArrayMap<String, SharedLibraryEntry>();
566
567    // All available activities, for your resolving pleasure.
568    final ActivityIntentResolver mActivities =
569            new ActivityIntentResolver();
570
571    // All available receivers, for your resolving pleasure.
572    final ActivityIntentResolver mReceivers =
573            new ActivityIntentResolver();
574
575    // All available services, for your resolving pleasure.
576    final ServiceIntentResolver mServices = new ServiceIntentResolver();
577
578    // All available providers, for your resolving pleasure.
579    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
580
581    // Mapping from provider base names (first directory in content URI codePath)
582    // to the provider information.
583    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
584            new ArrayMap<String, PackageParser.Provider>();
585
586    // Mapping from instrumentation class names to info about them.
587    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
588            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
589
590    // Mapping from permission names to info about them.
591    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
592            new ArrayMap<String, PackageParser.PermissionGroup>();
593
594    // Packages whose data we have transfered into another package, thus
595    // should no longer exist.
596    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
597
598    // Broadcast actions that are only available to the system.
599    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
600
601    /** List of packages waiting for verification. */
602    final SparseArray<PackageVerificationState> mPendingVerification
603            = new SparseArray<PackageVerificationState>();
604
605    /** Set of packages associated with each app op permission. */
606    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
607
608    final PackageInstallerService mInstallerService;
609
610    private final PackageDexOptimizer mPackageDexOptimizer;
611
612    private AtomicInteger mNextMoveId = new AtomicInteger();
613    private final MoveCallbacks mMoveCallbacks;
614
615    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
616
617    // Cache of users who need badging.
618    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
619
620    /** Token for keys in mPendingVerification. */
621    private int mPendingVerificationToken = 0;
622
623    volatile boolean mSystemReady;
624    volatile boolean mSafeMode;
625    volatile boolean mHasSystemUidErrors;
626
627    ApplicationInfo mAndroidApplication;
628    final ActivityInfo mResolveActivity = new ActivityInfo();
629    final ResolveInfo mResolveInfo = new ResolveInfo();
630    ComponentName mResolveComponentName;
631    PackageParser.Package mPlatformPackage;
632    ComponentName mCustomResolverComponentName;
633
634    boolean mResolverReplaced = false;
635
636    private final @Nullable ComponentName mIntentFilterVerifierComponent;
637    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
638
639    private int mIntentFilterVerificationToken = 0;
640
641    /** Component that knows whether or not an ephemeral application exists */
642    final ComponentName mEphemeralResolverComponent;
643    /** The service connection to the ephemeral resolver */
644    final EphemeralResolverConnection mEphemeralResolverConnection;
645
646    /** Component used to install ephemeral applications */
647    final ComponentName mEphemeralInstallerComponent;
648    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
649    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
650
651    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
652            = new SparseArray<IntentFilterVerificationState>();
653
654    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
655            new DefaultPermissionGrantPolicy(this);
656
657    // List of packages names to keep cached, even if they are uninstalled for all users
658    private List<String> mKeepUninstalledPackages;
659
660    private static class IFVerificationParams {
661        PackageParser.Package pkg;
662        boolean replacing;
663        int userId;
664        int verifierUid;
665
666        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
667                int _userId, int _verifierUid) {
668            pkg = _pkg;
669            replacing = _replacing;
670            userId = _userId;
671            replacing = _replacing;
672            verifierUid = _verifierUid;
673        }
674    }
675
676    private interface IntentFilterVerifier<T extends IntentFilter> {
677        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
678                                               T filter, String packageName);
679        void startVerifications(int userId);
680        void receiveVerificationResponse(int verificationId);
681    }
682
683    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
684        private Context mContext;
685        private ComponentName mIntentFilterVerifierComponent;
686        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
687
688        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
689            mContext = context;
690            mIntentFilterVerifierComponent = verifierComponent;
691        }
692
693        private String getDefaultScheme() {
694            return IntentFilter.SCHEME_HTTPS;
695        }
696
697        @Override
698        public void startVerifications(int userId) {
699            // Launch verifications requests
700            int count = mCurrentIntentFilterVerifications.size();
701            for (int n=0; n<count; n++) {
702                int verificationId = mCurrentIntentFilterVerifications.get(n);
703                final IntentFilterVerificationState ivs =
704                        mIntentFilterVerificationStates.get(verificationId);
705
706                String packageName = ivs.getPackageName();
707
708                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
709                final int filterCount = filters.size();
710                ArraySet<String> domainsSet = new ArraySet<>();
711                for (int m=0; m<filterCount; m++) {
712                    PackageParser.ActivityIntentInfo filter = filters.get(m);
713                    domainsSet.addAll(filter.getHostsList());
714                }
715                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
716                synchronized (mPackages) {
717                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
718                            packageName, domainsList) != null) {
719                        scheduleWriteSettingsLocked();
720                    }
721                }
722                sendVerificationRequest(userId, verificationId, ivs);
723            }
724            mCurrentIntentFilterVerifications.clear();
725        }
726
727        private void sendVerificationRequest(int userId, int verificationId,
728                IntentFilterVerificationState ivs) {
729
730            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
731            verificationIntent.putExtra(
732                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
733                    verificationId);
734            verificationIntent.putExtra(
735                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
736                    getDefaultScheme());
737            verificationIntent.putExtra(
738                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
739                    ivs.getHostsString());
740            verificationIntent.putExtra(
741                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
742                    ivs.getPackageName());
743            verificationIntent.setComponent(mIntentFilterVerifierComponent);
744            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
745
746            UserHandle user = new UserHandle(userId);
747            mContext.sendBroadcastAsUser(verificationIntent, user);
748            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
749                    "Sending IntentFilter verification broadcast");
750        }
751
752        public void receiveVerificationResponse(int verificationId) {
753            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
754
755            final boolean verified = ivs.isVerified();
756
757            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
758            final int count = filters.size();
759            if (DEBUG_DOMAIN_VERIFICATION) {
760                Slog.i(TAG, "Received verification response " + verificationId
761                        + " for " + count + " filters, verified=" + verified);
762            }
763            for (int n=0; n<count; n++) {
764                PackageParser.ActivityIntentInfo filter = filters.get(n);
765                filter.setVerified(verified);
766
767                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
768                        + " verified with result:" + verified + " and hosts:"
769                        + ivs.getHostsString());
770            }
771
772            mIntentFilterVerificationStates.remove(verificationId);
773
774            final String packageName = ivs.getPackageName();
775            IntentFilterVerificationInfo ivi = null;
776
777            synchronized (mPackages) {
778                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
779            }
780            if (ivi == null) {
781                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
782                        + verificationId + " packageName:" + packageName);
783                return;
784            }
785            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
786                    "Updating IntentFilterVerificationInfo for package " + packageName
787                            +" verificationId:" + verificationId);
788
789            synchronized (mPackages) {
790                if (verified) {
791                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
792                } else {
793                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
794                }
795                scheduleWriteSettingsLocked();
796
797                final int userId = ivs.getUserId();
798                if (userId != UserHandle.USER_ALL) {
799                    final int userStatus =
800                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
801
802                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
803                    boolean needUpdate = false;
804
805                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
806                    // already been set by the User thru the Disambiguation dialog
807                    switch (userStatus) {
808                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
809                            if (verified) {
810                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
811                            } else {
812                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
813                            }
814                            needUpdate = true;
815                            break;
816
817                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
818                            if (verified) {
819                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
820                                needUpdate = true;
821                            }
822                            break;
823
824                        default:
825                            // Nothing to do
826                    }
827
828                    if (needUpdate) {
829                        mSettings.updateIntentFilterVerificationStatusLPw(
830                                packageName, updatedStatus, userId);
831                        scheduleWritePackageRestrictionsLocked(userId);
832                    }
833                }
834            }
835        }
836
837        @Override
838        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
839                    ActivityIntentInfo filter, String packageName) {
840            if (!hasValidDomains(filter)) {
841                return false;
842            }
843            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
844            if (ivs == null) {
845                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
846                        packageName);
847            }
848            if (DEBUG_DOMAIN_VERIFICATION) {
849                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
850            }
851            ivs.addFilter(filter);
852            return true;
853        }
854
855        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
856                int userId, int verificationId, String packageName) {
857            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
858                    verifierUid, userId, packageName);
859            ivs.setPendingState();
860            synchronized (mPackages) {
861                mIntentFilterVerificationStates.append(verificationId, ivs);
862                mCurrentIntentFilterVerifications.add(verificationId);
863            }
864            return ivs;
865        }
866    }
867
868    private static boolean hasValidDomains(ActivityIntentInfo filter) {
869        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
870                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
871                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
872    }
873
874    // Set of pending broadcasts for aggregating enable/disable of components.
875    static class PendingPackageBroadcasts {
876        // for each user id, a map of <package name -> components within that package>
877        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
878
879        public PendingPackageBroadcasts() {
880            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
881        }
882
883        public ArrayList<String> get(int userId, String packageName) {
884            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
885            return packages.get(packageName);
886        }
887
888        public void put(int userId, String packageName, ArrayList<String> components) {
889            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
890            packages.put(packageName, components);
891        }
892
893        public void remove(int userId, String packageName) {
894            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
895            if (packages != null) {
896                packages.remove(packageName);
897            }
898        }
899
900        public void remove(int userId) {
901            mUidMap.remove(userId);
902        }
903
904        public int userIdCount() {
905            return mUidMap.size();
906        }
907
908        public int userIdAt(int n) {
909            return mUidMap.keyAt(n);
910        }
911
912        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
913            return mUidMap.get(userId);
914        }
915
916        public int size() {
917            // total number of pending broadcast entries across all userIds
918            int num = 0;
919            for (int i = 0; i< mUidMap.size(); i++) {
920                num += mUidMap.valueAt(i).size();
921            }
922            return num;
923        }
924
925        public void clear() {
926            mUidMap.clear();
927        }
928
929        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
930            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
931            if (map == null) {
932                map = new ArrayMap<String, ArrayList<String>>();
933                mUidMap.put(userId, map);
934            }
935            return map;
936        }
937    }
938    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
939
940    // Service Connection to remote media container service to copy
941    // package uri's from external media onto secure containers
942    // or internal storage.
943    private IMediaContainerService mContainerService = null;
944
945    static final int SEND_PENDING_BROADCAST = 1;
946    static final int MCS_BOUND = 3;
947    static final int END_COPY = 4;
948    static final int INIT_COPY = 5;
949    static final int MCS_UNBIND = 6;
950    static final int START_CLEANING_PACKAGE = 7;
951    static final int FIND_INSTALL_LOC = 8;
952    static final int POST_INSTALL = 9;
953    static final int MCS_RECONNECT = 10;
954    static final int MCS_GIVE_UP = 11;
955    static final int UPDATED_MEDIA_STATUS = 12;
956    static final int WRITE_SETTINGS = 13;
957    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
958    static final int PACKAGE_VERIFIED = 15;
959    static final int CHECK_PENDING_VERIFICATION = 16;
960    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
961    static final int INTENT_FILTER_VERIFIED = 18;
962
963    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
964
965    // Delay time in millisecs
966    static final int BROADCAST_DELAY = 10 * 1000;
967
968    static UserManagerService sUserManager;
969
970    // Stores a list of users whose package restrictions file needs to be updated
971    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
972
973    final private DefaultContainerConnection mDefContainerConn =
974            new DefaultContainerConnection();
975    class DefaultContainerConnection implements ServiceConnection {
976        public void onServiceConnected(ComponentName name, IBinder service) {
977            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
978            IMediaContainerService imcs =
979                IMediaContainerService.Stub.asInterface(service);
980            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
981        }
982
983        public void onServiceDisconnected(ComponentName name) {
984            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
985        }
986    }
987
988    // Recordkeeping of restore-after-install operations that are currently in flight
989    // between the Package Manager and the Backup Manager
990    static class PostInstallData {
991        public InstallArgs args;
992        public PackageInstalledInfo res;
993
994        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
995            args = _a;
996            res = _r;
997        }
998    }
999
1000    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1001    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1002
1003    // XML tags for backup/restore of various bits of state
1004    private static final String TAG_PREFERRED_BACKUP = "pa";
1005    private static final String TAG_DEFAULT_APPS = "da";
1006    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1007
1008    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1009    private static final String TAG_ALL_GRANTS = "rt-grants";
1010    private static final String TAG_GRANT = "grant";
1011    private static final String ATTR_PACKAGE_NAME = "pkg";
1012
1013    private static final String TAG_PERMISSION = "perm";
1014    private static final String ATTR_PERMISSION_NAME = "name";
1015    private static final String ATTR_IS_GRANTED = "g";
1016    private static final String ATTR_USER_SET = "set";
1017    private static final String ATTR_USER_FIXED = "fixed";
1018    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1019
1020    // System/policy permission grants are not backed up
1021    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1022            FLAG_PERMISSION_POLICY_FIXED
1023            | FLAG_PERMISSION_SYSTEM_FIXED
1024            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1025
1026    // And we back up these user-adjusted states
1027    private static final int USER_RUNTIME_GRANT_MASK =
1028            FLAG_PERMISSION_USER_SET
1029            | FLAG_PERMISSION_USER_FIXED
1030            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1031
1032    final @Nullable String mRequiredVerifierPackage;
1033    final @Nullable String mRequiredInstallerPackage;
1034
1035    private final PackageUsage mPackageUsage = new PackageUsage();
1036
1037    private class PackageUsage {
1038        private static final int WRITE_INTERVAL
1039            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1040
1041        private final Object mFileLock = new Object();
1042        private final AtomicLong mLastWritten = new AtomicLong(0);
1043        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1044
1045        private boolean mIsHistoricalPackageUsageAvailable = true;
1046
1047        boolean isHistoricalPackageUsageAvailable() {
1048            return mIsHistoricalPackageUsageAvailable;
1049        }
1050
1051        void write(boolean force) {
1052            if (force) {
1053                writeInternal();
1054                return;
1055            }
1056            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1057                && !DEBUG_DEXOPT) {
1058                return;
1059            }
1060            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1061                new Thread("PackageUsage_DiskWriter") {
1062                    @Override
1063                    public void run() {
1064                        try {
1065                            writeInternal();
1066                        } finally {
1067                            mBackgroundWriteRunning.set(false);
1068                        }
1069                    }
1070                }.start();
1071            }
1072        }
1073
1074        private void writeInternal() {
1075            synchronized (mPackages) {
1076                synchronized (mFileLock) {
1077                    AtomicFile file = getFile();
1078                    FileOutputStream f = null;
1079                    try {
1080                        f = file.startWrite();
1081                        BufferedOutputStream out = new BufferedOutputStream(f);
1082                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1083                        StringBuilder sb = new StringBuilder();
1084                        for (PackageParser.Package pkg : mPackages.values()) {
1085                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1086                                continue;
1087                            }
1088                            sb.setLength(0);
1089                            sb.append(pkg.packageName);
1090                            sb.append(' ');
1091                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1092                            sb.append('\n');
1093                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1094                        }
1095                        out.flush();
1096                        file.finishWrite(f);
1097                    } catch (IOException e) {
1098                        if (f != null) {
1099                            file.failWrite(f);
1100                        }
1101                        Log.e(TAG, "Failed to write package usage times", e);
1102                    }
1103                }
1104            }
1105            mLastWritten.set(SystemClock.elapsedRealtime());
1106        }
1107
1108        void readLP() {
1109            synchronized (mFileLock) {
1110                AtomicFile file = getFile();
1111                BufferedInputStream in = null;
1112                try {
1113                    in = new BufferedInputStream(file.openRead());
1114                    StringBuffer sb = new StringBuffer();
1115                    while (true) {
1116                        String packageName = readToken(in, sb, ' ');
1117                        if (packageName == null) {
1118                            break;
1119                        }
1120                        String timeInMillisString = readToken(in, sb, '\n');
1121                        if (timeInMillisString == null) {
1122                            throw new IOException("Failed to find last usage time for package "
1123                                                  + packageName);
1124                        }
1125                        PackageParser.Package pkg = mPackages.get(packageName);
1126                        if (pkg == null) {
1127                            continue;
1128                        }
1129                        long timeInMillis;
1130                        try {
1131                            timeInMillis = Long.parseLong(timeInMillisString);
1132                        } catch (NumberFormatException e) {
1133                            throw new IOException("Failed to parse " + timeInMillisString
1134                                                  + " as a long.", e);
1135                        }
1136                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1137                    }
1138                } catch (FileNotFoundException expected) {
1139                    mIsHistoricalPackageUsageAvailable = false;
1140                } catch (IOException e) {
1141                    Log.w(TAG, "Failed to read package usage times", e);
1142                } finally {
1143                    IoUtils.closeQuietly(in);
1144                }
1145            }
1146            mLastWritten.set(SystemClock.elapsedRealtime());
1147        }
1148
1149        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1150                throws IOException {
1151            sb.setLength(0);
1152            while (true) {
1153                int ch = in.read();
1154                if (ch == -1) {
1155                    if (sb.length() == 0) {
1156                        return null;
1157                    }
1158                    throw new IOException("Unexpected EOF");
1159                }
1160                if (ch == endOfToken) {
1161                    return sb.toString();
1162                }
1163                sb.append((char)ch);
1164            }
1165        }
1166
1167        private AtomicFile getFile() {
1168            File dataDir = Environment.getDataDirectory();
1169            File systemDir = new File(dataDir, "system");
1170            File fname = new File(systemDir, "package-usage.list");
1171            return new AtomicFile(fname);
1172        }
1173    }
1174
1175    class PackageHandler extends Handler {
1176        private boolean mBound = false;
1177        final ArrayList<HandlerParams> mPendingInstalls =
1178            new ArrayList<HandlerParams>();
1179
1180        private boolean connectToService() {
1181            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1182                    " DefaultContainerService");
1183            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1184            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1185            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1186                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1187                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1188                mBound = true;
1189                return true;
1190            }
1191            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1192            return false;
1193        }
1194
1195        private void disconnectService() {
1196            mContainerService = null;
1197            mBound = false;
1198            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1199            mContext.unbindService(mDefContainerConn);
1200            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1201        }
1202
1203        PackageHandler(Looper looper) {
1204            super(looper);
1205        }
1206
1207        public void handleMessage(Message msg) {
1208            try {
1209                doHandleMessage(msg);
1210            } finally {
1211                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1212            }
1213        }
1214
1215        void doHandleMessage(Message msg) {
1216            switch (msg.what) {
1217                case INIT_COPY: {
1218                    HandlerParams params = (HandlerParams) msg.obj;
1219                    int idx = mPendingInstalls.size();
1220                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1221                    // If a bind was already initiated we dont really
1222                    // need to do anything. The pending install
1223                    // will be processed later on.
1224                    if (!mBound) {
1225                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1226                                System.identityHashCode(mHandler));
1227                        // If this is the only one pending we might
1228                        // have to bind to the service again.
1229                        if (!connectToService()) {
1230                            Slog.e(TAG, "Failed to bind to media container service");
1231                            params.serviceError();
1232                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1233                                    System.identityHashCode(mHandler));
1234                            if (params.traceMethod != null) {
1235                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1236                                        params.traceCookie);
1237                            }
1238                            return;
1239                        } else {
1240                            // Once we bind to the service, the first
1241                            // pending request will be processed.
1242                            mPendingInstalls.add(idx, params);
1243                        }
1244                    } else {
1245                        mPendingInstalls.add(idx, params);
1246                        // Already bound to the service. Just make
1247                        // sure we trigger off processing the first request.
1248                        if (idx == 0) {
1249                            mHandler.sendEmptyMessage(MCS_BOUND);
1250                        }
1251                    }
1252                    break;
1253                }
1254                case MCS_BOUND: {
1255                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1256                    if (msg.obj != null) {
1257                        mContainerService = (IMediaContainerService) msg.obj;
1258                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1259                                System.identityHashCode(mHandler));
1260                    }
1261                    if (mContainerService == null) {
1262                        if (!mBound) {
1263                            // Something seriously wrong since we are not bound and we are not
1264                            // waiting for connection. Bail out.
1265                            Slog.e(TAG, "Cannot bind to media container service");
1266                            for (HandlerParams params : mPendingInstalls) {
1267                                // Indicate service bind error
1268                                params.serviceError();
1269                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1270                                        System.identityHashCode(params));
1271                                if (params.traceMethod != null) {
1272                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1273                                            params.traceMethod, params.traceCookie);
1274                                }
1275                                return;
1276                            }
1277                            mPendingInstalls.clear();
1278                        } else {
1279                            Slog.w(TAG, "Waiting to connect to media container service");
1280                        }
1281                    } else if (mPendingInstalls.size() > 0) {
1282                        HandlerParams params = mPendingInstalls.get(0);
1283                        if (params != null) {
1284                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1285                                    System.identityHashCode(params));
1286                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1287                            if (params.startCopy()) {
1288                                // We are done...  look for more work or to
1289                                // go idle.
1290                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1291                                        "Checking for more work or unbind...");
1292                                // Delete pending install
1293                                if (mPendingInstalls.size() > 0) {
1294                                    mPendingInstalls.remove(0);
1295                                }
1296                                if (mPendingInstalls.size() == 0) {
1297                                    if (mBound) {
1298                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1299                                                "Posting delayed MCS_UNBIND");
1300                                        removeMessages(MCS_UNBIND);
1301                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1302                                        // Unbind after a little delay, to avoid
1303                                        // continual thrashing.
1304                                        sendMessageDelayed(ubmsg, 10000);
1305                                    }
1306                                } else {
1307                                    // There are more pending requests in queue.
1308                                    // Just post MCS_BOUND message to trigger processing
1309                                    // of next pending install.
1310                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1311                                            "Posting MCS_BOUND for next work");
1312                                    mHandler.sendEmptyMessage(MCS_BOUND);
1313                                }
1314                            }
1315                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1316                        }
1317                    } else {
1318                        // Should never happen ideally.
1319                        Slog.w(TAG, "Empty queue");
1320                    }
1321                    break;
1322                }
1323                case MCS_RECONNECT: {
1324                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1325                    if (mPendingInstalls.size() > 0) {
1326                        if (mBound) {
1327                            disconnectService();
1328                        }
1329                        if (!connectToService()) {
1330                            Slog.e(TAG, "Failed to bind to media container service");
1331                            for (HandlerParams params : mPendingInstalls) {
1332                                // Indicate service bind error
1333                                params.serviceError();
1334                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1335                                        System.identityHashCode(params));
1336                            }
1337                            mPendingInstalls.clear();
1338                        }
1339                    }
1340                    break;
1341                }
1342                case MCS_UNBIND: {
1343                    // If there is no actual work left, then time to unbind.
1344                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1345
1346                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1347                        if (mBound) {
1348                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1349
1350                            disconnectService();
1351                        }
1352                    } else if (mPendingInstalls.size() > 0) {
1353                        // There are more pending requests in queue.
1354                        // Just post MCS_BOUND message to trigger processing
1355                        // of next pending install.
1356                        mHandler.sendEmptyMessage(MCS_BOUND);
1357                    }
1358
1359                    break;
1360                }
1361                case MCS_GIVE_UP: {
1362                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1363                    HandlerParams params = mPendingInstalls.remove(0);
1364                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1365                            System.identityHashCode(params));
1366                    break;
1367                }
1368                case SEND_PENDING_BROADCAST: {
1369                    String packages[];
1370                    ArrayList<String> components[];
1371                    int size = 0;
1372                    int uids[];
1373                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1374                    synchronized (mPackages) {
1375                        if (mPendingBroadcasts == null) {
1376                            return;
1377                        }
1378                        size = mPendingBroadcasts.size();
1379                        if (size <= 0) {
1380                            // Nothing to be done. Just return
1381                            return;
1382                        }
1383                        packages = new String[size];
1384                        components = new ArrayList[size];
1385                        uids = new int[size];
1386                        int i = 0;  // filling out the above arrays
1387
1388                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1389                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1390                            Iterator<Map.Entry<String, ArrayList<String>>> it
1391                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1392                                            .entrySet().iterator();
1393                            while (it.hasNext() && i < size) {
1394                                Map.Entry<String, ArrayList<String>> ent = it.next();
1395                                packages[i] = ent.getKey();
1396                                components[i] = ent.getValue();
1397                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1398                                uids[i] = (ps != null)
1399                                        ? UserHandle.getUid(packageUserId, ps.appId)
1400                                        : -1;
1401                                i++;
1402                            }
1403                        }
1404                        size = i;
1405                        mPendingBroadcasts.clear();
1406                    }
1407                    // Send broadcasts
1408                    for (int i = 0; i < size; i++) {
1409                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1410                    }
1411                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                    break;
1413                }
1414                case START_CLEANING_PACKAGE: {
1415                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1416                    final String packageName = (String)msg.obj;
1417                    final int userId = msg.arg1;
1418                    final boolean andCode = msg.arg2 != 0;
1419                    synchronized (mPackages) {
1420                        if (userId == UserHandle.USER_ALL) {
1421                            int[] users = sUserManager.getUserIds();
1422                            for (int user : users) {
1423                                mSettings.addPackageToCleanLPw(
1424                                        new PackageCleanItem(user, packageName, andCode));
1425                            }
1426                        } else {
1427                            mSettings.addPackageToCleanLPw(
1428                                    new PackageCleanItem(userId, packageName, andCode));
1429                        }
1430                    }
1431                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432                    startCleaningPackages();
1433                } break;
1434                case POST_INSTALL: {
1435                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1436
1437                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1438                    mRunningInstalls.delete(msg.arg1);
1439
1440                    if (data != null) {
1441                        InstallArgs args = data.args;
1442                        PackageInstalledInfo parentRes = data.res;
1443
1444                        final boolean grantPermissions = (args.installFlags
1445                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1446                        final boolean killApp = (args.installFlags
1447                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1448                        final String[] grantedPermissions = args.installGrantPermissions;
1449
1450                        // Handle the parent package
1451                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1452                                grantedPermissions, args.observer);
1453
1454                        // Handle the child packages
1455                        final int childCount = (parentRes.addedChildPackages != null)
1456                                ? parentRes.addedChildPackages.size() : 0;
1457                        for (int i = 0; i < childCount; i++) {
1458                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1459                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1460                                    grantedPermissions, args.observer);
1461                        }
1462
1463                        // Log tracing if needed
1464                        if (args.traceMethod != null) {
1465                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1466                                    args.traceCookie);
1467                        }
1468                    } else {
1469                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1470                    }
1471
1472                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1473                } break;
1474                case UPDATED_MEDIA_STATUS: {
1475                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1476                    boolean reportStatus = msg.arg1 == 1;
1477                    boolean doGc = msg.arg2 == 1;
1478                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1479                    if (doGc) {
1480                        // Force a gc to clear up stale containers.
1481                        Runtime.getRuntime().gc();
1482                    }
1483                    if (msg.obj != null) {
1484                        @SuppressWarnings("unchecked")
1485                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1486                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1487                        // Unload containers
1488                        unloadAllContainers(args);
1489                    }
1490                    if (reportStatus) {
1491                        try {
1492                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1493                            PackageHelper.getMountService().finishMediaUpdate();
1494                        } catch (RemoteException e) {
1495                            Log.e(TAG, "MountService not running?");
1496                        }
1497                    }
1498                } break;
1499                case WRITE_SETTINGS: {
1500                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1501                    synchronized (mPackages) {
1502                        removeMessages(WRITE_SETTINGS);
1503                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1504                        mSettings.writeLPr();
1505                        mDirtyUsers.clear();
1506                    }
1507                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1508                } break;
1509                case WRITE_PACKAGE_RESTRICTIONS: {
1510                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1511                    synchronized (mPackages) {
1512                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1513                        for (int userId : mDirtyUsers) {
1514                            mSettings.writePackageRestrictionsLPr(userId);
1515                        }
1516                        mDirtyUsers.clear();
1517                    }
1518                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1519                } break;
1520                case CHECK_PENDING_VERIFICATION: {
1521                    final int verificationId = msg.arg1;
1522                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1523
1524                    if ((state != null) && !state.timeoutExtended()) {
1525                        final InstallArgs args = state.getInstallArgs();
1526                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1527
1528                        Slog.i(TAG, "Verification timed out for " + originUri);
1529                        mPendingVerification.remove(verificationId);
1530
1531                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1532
1533                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1534                            Slog.i(TAG, "Continuing with installation of " + originUri);
1535                            state.setVerifierResponse(Binder.getCallingUid(),
1536                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1537                            broadcastPackageVerified(verificationId, originUri,
1538                                    PackageManager.VERIFICATION_ALLOW,
1539                                    state.getInstallArgs().getUser());
1540                            try {
1541                                ret = args.copyApk(mContainerService, true);
1542                            } catch (RemoteException e) {
1543                                Slog.e(TAG, "Could not contact the ContainerService");
1544                            }
1545                        } else {
1546                            broadcastPackageVerified(verificationId, originUri,
1547                                    PackageManager.VERIFICATION_REJECT,
1548                                    state.getInstallArgs().getUser());
1549                        }
1550
1551                        Trace.asyncTraceEnd(
1552                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1553
1554                        processPendingInstall(args, ret);
1555                        mHandler.sendEmptyMessage(MCS_UNBIND);
1556                    }
1557                    break;
1558                }
1559                case PACKAGE_VERIFIED: {
1560                    final int verificationId = msg.arg1;
1561
1562                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1563                    if (state == null) {
1564                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1565                        break;
1566                    }
1567
1568                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1569
1570                    state.setVerifierResponse(response.callerUid, response.code);
1571
1572                    if (state.isVerificationComplete()) {
1573                        mPendingVerification.remove(verificationId);
1574
1575                        final InstallArgs args = state.getInstallArgs();
1576                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1577
1578                        int ret;
1579                        if (state.isInstallAllowed()) {
1580                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1581                            broadcastPackageVerified(verificationId, originUri,
1582                                    response.code, state.getInstallArgs().getUser());
1583                            try {
1584                                ret = args.copyApk(mContainerService, true);
1585                            } catch (RemoteException e) {
1586                                Slog.e(TAG, "Could not contact the ContainerService");
1587                            }
1588                        } else {
1589                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1590                        }
1591
1592                        Trace.asyncTraceEnd(
1593                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1594
1595                        processPendingInstall(args, ret);
1596                        mHandler.sendEmptyMessage(MCS_UNBIND);
1597                    }
1598
1599                    break;
1600                }
1601                case START_INTENT_FILTER_VERIFICATIONS: {
1602                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1603                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1604                            params.replacing, params.pkg);
1605                    break;
1606                }
1607                case INTENT_FILTER_VERIFIED: {
1608                    final int verificationId = msg.arg1;
1609
1610                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1611                            verificationId);
1612                    if (state == null) {
1613                        Slog.w(TAG, "Invalid IntentFilter verification token "
1614                                + verificationId + " received");
1615                        break;
1616                    }
1617
1618                    final int userId = state.getUserId();
1619
1620                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1621                            "Processing IntentFilter verification with token:"
1622                            + verificationId + " and userId:" + userId);
1623
1624                    final IntentFilterVerificationResponse response =
1625                            (IntentFilterVerificationResponse) msg.obj;
1626
1627                    state.setVerifierResponse(response.callerUid, response.code);
1628
1629                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1630                            "IntentFilter verification with token:" + verificationId
1631                            + " and userId:" + userId
1632                            + " is settings verifier response with response code:"
1633                            + response.code);
1634
1635                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1636                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1637                                + response.getFailedDomainsString());
1638                    }
1639
1640                    if (state.isVerificationComplete()) {
1641                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1642                    } else {
1643                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1644                                "IntentFilter verification with token:" + verificationId
1645                                + " was not said to be complete");
1646                    }
1647
1648                    break;
1649                }
1650            }
1651        }
1652    }
1653
1654    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1655            boolean killApp, String[] grantedPermissions,
1656            IPackageInstallObserver2 installObserver) {
1657        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1658            // Send the removed broadcasts
1659            if (res.removedInfo != null) {
1660                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1661            }
1662
1663            // Now that we successfully installed the package, grant runtime
1664            // permissions if requested before broadcasting the install.
1665            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1666                    >= Build.VERSION_CODES.M) {
1667                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1668            }
1669
1670            final boolean update = res.removedInfo != null
1671                    && res.removedInfo.removedPackage != null;
1672
1673            // If this is the first time we have child packages for a disabled privileged
1674            // app that had no children, we grant requested runtime permissions to the new
1675            // children if the parent on the system image had them already granted.
1676            if (res.pkg.parentPackage != null) {
1677                synchronized (mPackages) {
1678                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1679                }
1680            }
1681
1682            synchronized (mPackages) {
1683                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1684            }
1685
1686            final String packageName = res.pkg.applicationInfo.packageName;
1687            Bundle extras = new Bundle(1);
1688            extras.putInt(Intent.EXTRA_UID, res.uid);
1689
1690            // Determine the set of users who are adding this package for
1691            // the first time vs. those who are seeing an update.
1692            int[] firstUsers = EMPTY_INT_ARRAY;
1693            int[] updateUsers = EMPTY_INT_ARRAY;
1694            if (res.origUsers == null || res.origUsers.length == 0) {
1695                firstUsers = res.newUsers;
1696            } else {
1697                for (int newUser : res.newUsers) {
1698                    boolean isNew = true;
1699                    for (int origUser : res.origUsers) {
1700                        if (origUser == newUser) {
1701                            isNew = false;
1702                            break;
1703                        }
1704                    }
1705                    if (isNew) {
1706                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1707                    } else {
1708                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1709                    }
1710                }
1711            }
1712
1713            // Send installed broadcasts if the install/update is not ephemeral
1714            if (!isEphemeral(res.pkg)) {
1715                // Send added for users that see the package for the first time
1716                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1717                        extras, 0 /*flags*/, null /*targetPackage*/,
1718                        null /*finishedReceiver*/, firstUsers);
1719
1720                // Send added for users that don't see the package for the first time
1721                if (update) {
1722                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1723                }
1724                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1725                        extras, 0 /*flags*/, null /*targetPackage*/,
1726                        null /*finishedReceiver*/, updateUsers);
1727
1728                // Send replaced for users that don't see the package for the first time
1729                if (update) {
1730                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1731                            packageName, extras, 0 /*flags*/,
1732                            null /*targetPackage*/, null /*finishedReceiver*/,
1733                            updateUsers);
1734                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1735                            null /*package*/, null /*extras*/, 0 /*flags*/,
1736                            packageName /*targetPackage*/,
1737                            null /*finishedReceiver*/, updateUsers);
1738                }
1739
1740                // Send broadcast package appeared if forward locked/external for all users
1741                // treat asec-hosted packages like removable media on upgrade
1742                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1743                    if (DEBUG_INSTALL) {
1744                        Slog.i(TAG, "upgrading pkg " + res.pkg
1745                                + " is ASEC-hosted -> AVAILABLE");
1746                    }
1747                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1748                    ArrayList<String> pkgList = new ArrayList<>(1);
1749                    pkgList.add(packageName);
1750                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1751                }
1752            }
1753
1754            // Work that needs to happen on first install within each user
1755            if (firstUsers != null && firstUsers.length > 0) {
1756                synchronized (mPackages) {
1757                    for (int userId : firstUsers) {
1758                        // If this app is a browser and it's newly-installed for some
1759                        // users, clear any default-browser state in those users. The
1760                        // app's nature doesn't depend on the user, so we can just check
1761                        // its browser nature in any user and generalize.
1762                        if (packageIsBrowser(packageName, userId)) {
1763                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1764                        }
1765
1766                        // We may also need to apply pending (restored) runtime
1767                        // permission grants within these users.
1768                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1769                    }
1770                }
1771            }
1772
1773            // Log current value of "unknown sources" setting
1774            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1775                    getUnknownSourcesSettings());
1776
1777            // Force a gc to clear up things
1778            Runtime.getRuntime().gc();
1779
1780            // Remove the replaced package's older resources safely now
1781            // We delete after a gc for applications  on sdcard.
1782            if (res.removedInfo != null && res.removedInfo.args != null) {
1783                synchronized (mInstallLock) {
1784                    res.removedInfo.args.doPostDeleteLI(true);
1785                }
1786            }
1787        }
1788
1789        // If someone is watching installs - notify them
1790        if (installObserver != null) {
1791            try {
1792                Bundle extras = extrasForInstallResult(res);
1793                installObserver.onPackageInstalled(res.name, res.returnCode,
1794                        res.returnMsg, extras);
1795            } catch (RemoteException e) {
1796                Slog.i(TAG, "Observer no longer exists.");
1797            }
1798        }
1799    }
1800
1801    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1802            PackageParser.Package pkg) {
1803        if (pkg.parentPackage == null) {
1804            return;
1805        }
1806        if (pkg.requestedPermissions == null) {
1807            return;
1808        }
1809        final PackageSetting disabledSysParentPs = mSettings
1810                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1811        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1812                || !disabledSysParentPs.isPrivileged()
1813                || (disabledSysParentPs.childPackageNames != null
1814                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1815            return;
1816        }
1817        final int[] allUserIds = sUserManager.getUserIds();
1818        final int permCount = pkg.requestedPermissions.size();
1819        for (int i = 0; i < permCount; i++) {
1820            String permission = pkg.requestedPermissions.get(i);
1821            BasePermission bp = mSettings.mPermissions.get(permission);
1822            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1823                continue;
1824            }
1825            for (int userId : allUserIds) {
1826                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1827                        permission, userId)) {
1828                    grantRuntimePermission(pkg.packageName, permission, userId);
1829                }
1830            }
1831        }
1832    }
1833
1834    private StorageEventListener mStorageListener = new StorageEventListener() {
1835        @Override
1836        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1837            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1838                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1839                    final String volumeUuid = vol.getFsUuid();
1840
1841                    // Clean up any users or apps that were removed or recreated
1842                    // while this volume was missing
1843                    reconcileUsers(volumeUuid);
1844                    reconcileApps(volumeUuid);
1845
1846                    // Clean up any install sessions that expired or were
1847                    // cancelled while this volume was missing
1848                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1849
1850                    loadPrivatePackages(vol);
1851
1852                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1853                    unloadPrivatePackages(vol);
1854                }
1855            }
1856
1857            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1858                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1859                    updateExternalMediaStatus(true, false);
1860                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1861                    updateExternalMediaStatus(false, false);
1862                }
1863            }
1864        }
1865
1866        @Override
1867        public void onVolumeForgotten(String fsUuid) {
1868            if (TextUtils.isEmpty(fsUuid)) {
1869                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1870                return;
1871            }
1872
1873            // Remove any apps installed on the forgotten volume
1874            synchronized (mPackages) {
1875                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1876                for (PackageSetting ps : packages) {
1877                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1878                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1879                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1880                }
1881
1882                mSettings.onVolumeForgotten(fsUuid);
1883                mSettings.writeLPr();
1884            }
1885        }
1886    };
1887
1888    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1889            String[] grantedPermissions) {
1890        for (int userId : userIds) {
1891            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1892        }
1893
1894        // We could have touched GID membership, so flush out packages.list
1895        synchronized (mPackages) {
1896            mSettings.writePackageListLPr();
1897        }
1898    }
1899
1900    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1901            String[] grantedPermissions) {
1902        SettingBase sb = (SettingBase) pkg.mExtras;
1903        if (sb == null) {
1904            return;
1905        }
1906
1907        PermissionsState permissionsState = sb.getPermissionsState();
1908
1909        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1910                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1911
1912        synchronized (mPackages) {
1913            for (String permission : pkg.requestedPermissions) {
1914                BasePermission bp = mSettings.mPermissions.get(permission);
1915                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1916                        && (grantedPermissions == null
1917                               || ArrayUtils.contains(grantedPermissions, permission))) {
1918                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1919                    // Installer cannot change immutable permissions.
1920                    if ((flags & immutableFlags) == 0) {
1921                        grantRuntimePermission(pkg.packageName, permission, userId);
1922                    }
1923                }
1924            }
1925        }
1926    }
1927
1928    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1929        Bundle extras = null;
1930        switch (res.returnCode) {
1931            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1932                extras = new Bundle();
1933                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1934                        res.origPermission);
1935                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1936                        res.origPackage);
1937                break;
1938            }
1939            case PackageManager.INSTALL_SUCCEEDED: {
1940                extras = new Bundle();
1941                extras.putBoolean(Intent.EXTRA_REPLACING,
1942                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1943                break;
1944            }
1945        }
1946        return extras;
1947    }
1948
1949    void scheduleWriteSettingsLocked() {
1950        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1951            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1952        }
1953    }
1954
1955    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1956        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1957        scheduleWritePackageRestrictionsLocked(userId);
1958    }
1959
1960    void scheduleWritePackageRestrictionsLocked(int userId) {
1961        final int[] userIds = (userId == UserHandle.USER_ALL)
1962                ? sUserManager.getUserIds() : new int[]{userId};
1963        for (int nextUserId : userIds) {
1964            if (!sUserManager.exists(nextUserId)) return;
1965            mDirtyUsers.add(nextUserId);
1966            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1967                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1968            }
1969        }
1970    }
1971
1972    public static PackageManagerService main(Context context, Installer installer,
1973            boolean factoryTest, boolean onlyCore) {
1974        // Self-check for initial settings.
1975        PackageManagerServiceCompilerMapping.checkProperties();
1976
1977        PackageManagerService m = new PackageManagerService(context, installer,
1978                factoryTest, onlyCore);
1979        m.enableSystemUserPackages();
1980        ServiceManager.addService("package", m);
1981        return m;
1982    }
1983
1984    private void enableSystemUserPackages() {
1985        if (!UserManager.isSplitSystemUser()) {
1986            return;
1987        }
1988        // For system user, enable apps based on the following conditions:
1989        // - app is whitelisted or belong to one of these groups:
1990        //   -- system app which has no launcher icons
1991        //   -- system app which has INTERACT_ACROSS_USERS permission
1992        //   -- system IME app
1993        // - app is not in the blacklist
1994        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1995        Set<String> enableApps = new ArraySet<>();
1996        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1997                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1998                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1999        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2000        enableApps.addAll(wlApps);
2001        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2002                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2003        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2004        enableApps.removeAll(blApps);
2005        Log.i(TAG, "Applications installed for system user: " + enableApps);
2006        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2007                UserHandle.SYSTEM);
2008        final int allAppsSize = allAps.size();
2009        synchronized (mPackages) {
2010            for (int i = 0; i < allAppsSize; i++) {
2011                String pName = allAps.get(i);
2012                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2013                // Should not happen, but we shouldn't be failing if it does
2014                if (pkgSetting == null) {
2015                    continue;
2016                }
2017                boolean install = enableApps.contains(pName);
2018                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2019                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2020                            + " for system user");
2021                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2022                }
2023            }
2024        }
2025    }
2026
2027    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2028        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2029                Context.DISPLAY_SERVICE);
2030        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2031    }
2032
2033    public PackageManagerService(Context context, Installer installer,
2034            boolean factoryTest, boolean onlyCore) {
2035        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2036                SystemClock.uptimeMillis());
2037
2038        if (mSdkVersion <= 0) {
2039            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2040        }
2041
2042        mContext = context;
2043        mFactoryTest = factoryTest;
2044        mOnlyCore = onlyCore;
2045        mMetrics = new DisplayMetrics();
2046        mSettings = new Settings(mPackages);
2047        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2048                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2049        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2050                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2051        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2052                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2053        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2054                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2055        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2056                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2057        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2058                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2059
2060        String separateProcesses = SystemProperties.get("debug.separate_processes");
2061        if (separateProcesses != null && separateProcesses.length() > 0) {
2062            if ("*".equals(separateProcesses)) {
2063                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2064                mSeparateProcesses = null;
2065                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2066            } else {
2067                mDefParseFlags = 0;
2068                mSeparateProcesses = separateProcesses.split(",");
2069                Slog.w(TAG, "Running with debug.separate_processes: "
2070                        + separateProcesses);
2071            }
2072        } else {
2073            mDefParseFlags = 0;
2074            mSeparateProcesses = null;
2075        }
2076
2077        mInstaller = installer;
2078        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2079                "*dexopt*");
2080        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2081
2082        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2083                FgThread.get().getLooper());
2084
2085        getDefaultDisplayMetrics(context, mMetrics);
2086
2087        SystemConfig systemConfig = SystemConfig.getInstance();
2088        mGlobalGids = systemConfig.getGlobalGids();
2089        mSystemPermissions = systemConfig.getSystemPermissions();
2090        mAvailableFeatures = systemConfig.getAvailableFeatures();
2091
2092        synchronized (mInstallLock) {
2093        // writer
2094        synchronized (mPackages) {
2095            mHandlerThread = new ServiceThread(TAG,
2096                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2097            mHandlerThread.start();
2098            mHandler = new PackageHandler(mHandlerThread.getLooper());
2099            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2100
2101            File dataDir = Environment.getDataDirectory();
2102            mAppInstallDir = new File(dataDir, "app");
2103            mAppLib32InstallDir = new File(dataDir, "app-lib");
2104            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2105            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2106            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2107
2108            sUserManager = new UserManagerService(context, this, mPackages);
2109
2110            // Propagate permission configuration in to package manager.
2111            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2112                    = systemConfig.getPermissions();
2113            for (int i=0; i<permConfig.size(); i++) {
2114                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2115                BasePermission bp = mSettings.mPermissions.get(perm.name);
2116                if (bp == null) {
2117                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2118                    mSettings.mPermissions.put(perm.name, bp);
2119                }
2120                if (perm.gids != null) {
2121                    bp.setGids(perm.gids, perm.perUser);
2122                }
2123            }
2124
2125            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2126            for (int i=0; i<libConfig.size(); i++) {
2127                mSharedLibraries.put(libConfig.keyAt(i),
2128                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2129            }
2130
2131            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2132
2133            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2134
2135            String customResolverActivity = Resources.getSystem().getString(
2136                    R.string.config_customResolverActivity);
2137            if (TextUtils.isEmpty(customResolverActivity)) {
2138                customResolverActivity = null;
2139            } else {
2140                mCustomResolverComponentName = ComponentName.unflattenFromString(
2141                        customResolverActivity);
2142            }
2143
2144            long startTime = SystemClock.uptimeMillis();
2145
2146            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2147                    startTime);
2148
2149            // Set flag to monitor and not change apk file paths when
2150            // scanning install directories.
2151            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2152
2153            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2154            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2155
2156            if (bootClassPath == null) {
2157                Slog.w(TAG, "No BOOTCLASSPATH found!");
2158            }
2159
2160            if (systemServerClassPath == null) {
2161                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2162            }
2163
2164            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2165            final String[] dexCodeInstructionSets =
2166                    getDexCodeInstructionSets(
2167                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2168
2169            /**
2170             * Ensure all external libraries have had dexopt run on them.
2171             */
2172            if (mSharedLibraries.size() > 0) {
2173                // NOTE: For now, we're compiling these system "shared libraries"
2174                // (and framework jars) into all available architectures. It's possible
2175                // to compile them only when we come across an app that uses them (there's
2176                // already logic for that in scanPackageLI) but that adds some complexity.
2177                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2178                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2179                        final String lib = libEntry.path;
2180                        if (lib == null) {
2181                            continue;
2182                        }
2183
2184                        try {
2185                            // Shared libraries do not have profiles so we perform a full
2186                            // AOT compilation (if needed).
2187                            int dexoptNeeded = DexFile.getDexOptNeeded(
2188                                    lib, dexCodeInstructionSet,
2189                                    getCompilerFilterForReason(REASON_SHARED_APK),
2190                                    false /* newProfile */);
2191                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2192                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2193                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2194                                        getCompilerFilterForReason(REASON_SHARED_APK),
2195                                        StorageManager.UUID_PRIVATE_INTERNAL);
2196                            }
2197                        } catch (FileNotFoundException e) {
2198                            Slog.w(TAG, "Library not found: " + lib);
2199                        } catch (IOException | InstallerException e) {
2200                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2201                                    + e.getMessage());
2202                        }
2203                    }
2204                }
2205            }
2206
2207            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2208
2209            final VersionInfo ver = mSettings.getInternalVersion();
2210            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2211
2212            // when upgrading from pre-M, promote system app permissions from install to runtime
2213            mPromoteSystemApps =
2214                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2215
2216            // save off the names of pre-existing system packages prior to scanning; we don't
2217            // want to automatically grant runtime permissions for new system apps
2218            if (mPromoteSystemApps) {
2219                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2220                while (pkgSettingIter.hasNext()) {
2221                    PackageSetting ps = pkgSettingIter.next();
2222                    if (isSystemApp(ps)) {
2223                        mExistingSystemPackages.add(ps.name);
2224                    }
2225                }
2226            }
2227
2228            // When upgrading from pre-N, we need to handle package extraction like first boot,
2229            // as there is no profiling data available.
2230            mIsPreNUpgrade = !mSettings.isNWorkDone();
2231            mSettings.setNWorkDone();
2232
2233            // Collect vendor overlay packages.
2234            // (Do this before scanning any apps.)
2235            // For security and version matching reason, only consider
2236            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2237            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2238            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2239                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2240
2241            // Find base frameworks (resource packages without code).
2242            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2243                    | PackageParser.PARSE_IS_SYSTEM_DIR
2244                    | PackageParser.PARSE_IS_PRIVILEGED,
2245                    scanFlags | SCAN_NO_DEX, 0);
2246
2247            // Collected privileged system packages.
2248            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2249            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2250                    | PackageParser.PARSE_IS_SYSTEM_DIR
2251                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2252
2253            // Collect ordinary system packages.
2254            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2255            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2256                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2257
2258            // Collect all vendor packages.
2259            File vendorAppDir = new File("/vendor/app");
2260            try {
2261                vendorAppDir = vendorAppDir.getCanonicalFile();
2262            } catch (IOException e) {
2263                // failed to look up canonical path, continue with original one
2264            }
2265            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2266                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2267
2268            // Collect all OEM packages.
2269            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2270            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2271                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2272
2273            // Prune any system packages that no longer exist.
2274            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2275            if (!mOnlyCore) {
2276                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2277                while (psit.hasNext()) {
2278                    PackageSetting ps = psit.next();
2279
2280                    /*
2281                     * If this is not a system app, it can't be a
2282                     * disable system app.
2283                     */
2284                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2285                        continue;
2286                    }
2287
2288                    /*
2289                     * If the package is scanned, it's not erased.
2290                     */
2291                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2292                    if (scannedPkg != null) {
2293                        /*
2294                         * If the system app is both scanned and in the
2295                         * disabled packages list, then it must have been
2296                         * added via OTA. Remove it from the currently
2297                         * scanned package so the previously user-installed
2298                         * application can be scanned.
2299                         */
2300                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2301                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2302                                    + ps.name + "; removing system app.  Last known codePath="
2303                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2304                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2305                                    + scannedPkg.mVersionCode);
2306                            removePackageLI(scannedPkg, true);
2307                            mExpectingBetter.put(ps.name, ps.codePath);
2308                        }
2309
2310                        continue;
2311                    }
2312
2313                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2314                        psit.remove();
2315                        logCriticalInfo(Log.WARN, "System package " + ps.name
2316                                + " no longer exists; wiping its data");
2317                        removeDataDirsLI(null, ps.name);
2318                    } else {
2319                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2320                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2321                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2322                        }
2323                    }
2324                }
2325            }
2326
2327            //look for any incomplete package installations
2328            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2329            //clean up list
2330            for(int i = 0; i < deletePkgsList.size(); i++) {
2331                //clean up here
2332                cleanupInstallFailedPackage(deletePkgsList.get(i));
2333            }
2334            //delete tmp files
2335            deleteTempPackageFiles();
2336
2337            // Remove any shared userIDs that have no associated packages
2338            mSettings.pruneSharedUsersLPw();
2339
2340            if (!mOnlyCore) {
2341                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2342                        SystemClock.uptimeMillis());
2343                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2344
2345                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2346                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2347
2348                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2349                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2350
2351                /**
2352                 * Remove disable package settings for any updated system
2353                 * apps that were removed via an OTA. If they're not a
2354                 * previously-updated app, remove them completely.
2355                 * Otherwise, just revoke their system-level permissions.
2356                 */
2357                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2358                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2359                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2360
2361                    String msg;
2362                    if (deletedPkg == null) {
2363                        msg = "Updated system package " + deletedAppName
2364                                + " no longer exists; wiping its data";
2365                        removeDataDirsLI(null, deletedAppName);
2366                    } else {
2367                        msg = "Updated system app + " + deletedAppName
2368                                + " no longer present; removing system privileges for "
2369                                + deletedAppName;
2370
2371                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2372
2373                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2374                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2375                    }
2376                    logCriticalInfo(Log.WARN, msg);
2377                }
2378
2379                /**
2380                 * Make sure all system apps that we expected to appear on
2381                 * the userdata partition actually showed up. If they never
2382                 * appeared, crawl back and revive the system version.
2383                 */
2384                for (int i = 0; i < mExpectingBetter.size(); i++) {
2385                    final String packageName = mExpectingBetter.keyAt(i);
2386                    if (!mPackages.containsKey(packageName)) {
2387                        final File scanFile = mExpectingBetter.valueAt(i);
2388
2389                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2390                                + " but never showed up; reverting to system");
2391
2392                        final int reparseFlags;
2393                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2394                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2395                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2396                                    | PackageParser.PARSE_IS_PRIVILEGED;
2397                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2398                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2399                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2400                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2401                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2402                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2403                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2404                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2405                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2406                        } else {
2407                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2408                            continue;
2409                        }
2410
2411                        mSettings.enableSystemPackageLPw(packageName);
2412
2413                        try {
2414                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2415                        } catch (PackageManagerException e) {
2416                            Slog.e(TAG, "Failed to parse original system package: "
2417                                    + e.getMessage());
2418                        }
2419                    }
2420                }
2421            }
2422            mExpectingBetter.clear();
2423
2424            // Now that we know all of the shared libraries, update all clients to have
2425            // the correct library paths.
2426            updateAllSharedLibrariesLPw();
2427
2428            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2429                // NOTE: We ignore potential failures here during a system scan (like
2430                // the rest of the commands above) because there's precious little we
2431                // can do about it. A settings error is reported, though.
2432                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2433                        false /* boot complete */);
2434            }
2435
2436            // Now that we know all the packages we are keeping,
2437            // read and update their last usage times.
2438            mPackageUsage.readLP();
2439
2440            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2441                    SystemClock.uptimeMillis());
2442            Slog.i(TAG, "Time to scan packages: "
2443                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2444                    + " seconds");
2445
2446            // If the platform SDK has changed since the last time we booted,
2447            // we need to re-grant app permission to catch any new ones that
2448            // appear.  This is really a hack, and means that apps can in some
2449            // cases get permissions that the user didn't initially explicitly
2450            // allow...  it would be nice to have some better way to handle
2451            // this situation.
2452            int updateFlags = UPDATE_PERMISSIONS_ALL;
2453            if (ver.sdkVersion != mSdkVersion) {
2454                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2455                        + mSdkVersion + "; regranting permissions for internal storage");
2456                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2457            }
2458            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2459            ver.sdkVersion = mSdkVersion;
2460
2461            // If this is the first boot or an update from pre-M, and it is a normal
2462            // boot, then we need to initialize the default preferred apps across
2463            // all defined users.
2464            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2465                for (UserInfo user : sUserManager.getUsers(true)) {
2466                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2467                    applyFactoryDefaultBrowserLPw(user.id);
2468                    primeDomainVerificationsLPw(user.id);
2469                }
2470            }
2471
2472            // Prepare storage for system user really early during boot,
2473            // since core system apps like SettingsProvider and SystemUI
2474            // can't wait for user to start
2475            final int storageFlags;
2476            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2477                storageFlags = StorageManager.FLAG_STORAGE_DE;
2478            } else {
2479                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2480            }
2481            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2482                    storageFlags);
2483
2484            // If this is first boot after an OTA, and a normal boot, then
2485            // we need to clear code cache directories.
2486            if (mIsUpgrade && !onlyCore) {
2487                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2488                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2489                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2490                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2491                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2492                    }
2493                }
2494                ver.fingerprint = Build.FINGERPRINT;
2495            }
2496
2497            checkDefaultBrowser();
2498
2499            // clear only after permissions and other defaults have been updated
2500            mExistingSystemPackages.clear();
2501            mPromoteSystemApps = false;
2502
2503            // All the changes are done during package scanning.
2504            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2505
2506            // can downgrade to reader
2507            mSettings.writeLPr();
2508
2509            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2510                    SystemClock.uptimeMillis());
2511
2512            if (!mOnlyCore) {
2513                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2514                mRequiredInstallerPackage = getRequiredInstallerLPr();
2515                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2516                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2517                        mIntentFilterVerifierComponent);
2518            } else {
2519                mRequiredVerifierPackage = null;
2520                mRequiredInstallerPackage = null;
2521                mIntentFilterVerifierComponent = null;
2522                mIntentFilterVerifier = null;
2523            }
2524
2525            mInstallerService = new PackageInstallerService(context, this);
2526
2527            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2528            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2529            // both the installer and resolver must be present to enable ephemeral
2530            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2531                if (DEBUG_EPHEMERAL) {
2532                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2533                            + " installer:" + ephemeralInstallerComponent);
2534                }
2535                mEphemeralResolverComponent = ephemeralResolverComponent;
2536                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2537                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2538                mEphemeralResolverConnection =
2539                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2540            } else {
2541                if (DEBUG_EPHEMERAL) {
2542                    final String missingComponent =
2543                            (ephemeralResolverComponent == null)
2544                            ? (ephemeralInstallerComponent == null)
2545                                    ? "resolver and installer"
2546                                    : "resolver"
2547                            : "installer";
2548                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2549                }
2550                mEphemeralResolverComponent = null;
2551                mEphemeralInstallerComponent = null;
2552                mEphemeralResolverConnection = null;
2553            }
2554
2555            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2556        } // synchronized (mPackages)
2557        } // synchronized (mInstallLock)
2558
2559        // Now after opening every single application zip, make sure they
2560        // are all flushed.  Not really needed, but keeps things nice and
2561        // tidy.
2562        Runtime.getRuntime().gc();
2563
2564        // The initial scanning above does many calls into installd while
2565        // holding the mPackages lock, but we're mostly interested in yelling
2566        // once we have a booted system.
2567        mInstaller.setWarnIfHeld(mPackages);
2568
2569        // Expose private service for system components to use.
2570        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2571    }
2572
2573    @Override
2574    public boolean isFirstBoot() {
2575        return !mRestoredSettings;
2576    }
2577
2578    @Override
2579    public boolean isOnlyCoreApps() {
2580        return mOnlyCore;
2581    }
2582
2583    @Override
2584    public boolean isUpgrade() {
2585        return mIsUpgrade;
2586    }
2587
2588    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2589        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2590
2591        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2592                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2593                UserHandle.USER_SYSTEM);
2594        if (matches.size() == 1) {
2595            return matches.get(0).getComponentInfo().packageName;
2596        } else {
2597            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2598            return null;
2599        }
2600    }
2601
2602    private @NonNull String getRequiredInstallerLPr() {
2603        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2604        intent.addCategory(Intent.CATEGORY_DEFAULT);
2605        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2606
2607        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2608                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2609                UserHandle.USER_SYSTEM);
2610        if (matches.size() == 1) {
2611            return matches.get(0).getComponentInfo().packageName;
2612        } else {
2613            throw new RuntimeException("There must be exactly one installer; found " + matches);
2614        }
2615    }
2616
2617    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2618        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2619
2620        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2621                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2622                UserHandle.USER_SYSTEM);
2623        ResolveInfo best = null;
2624        final int N = matches.size();
2625        for (int i = 0; i < N; i++) {
2626            final ResolveInfo cur = matches.get(i);
2627            final String packageName = cur.getComponentInfo().packageName;
2628            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2629                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2630                continue;
2631            }
2632
2633            if (best == null || cur.priority > best.priority) {
2634                best = cur;
2635            }
2636        }
2637
2638        if (best != null) {
2639            return best.getComponentInfo().getComponentName();
2640        } else {
2641            throw new RuntimeException("There must be at least one intent filter verifier");
2642        }
2643    }
2644
2645    private @Nullable ComponentName getEphemeralResolverLPr() {
2646        final String[] packageArray =
2647                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2648        if (packageArray.length == 0) {
2649            if (DEBUG_EPHEMERAL) {
2650                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2651            }
2652            return null;
2653        }
2654
2655        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2656        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2657                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2658                UserHandle.USER_SYSTEM);
2659
2660        final int N = resolvers.size();
2661        if (N == 0) {
2662            if (DEBUG_EPHEMERAL) {
2663                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2664            }
2665            return null;
2666        }
2667
2668        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2669        for (int i = 0; i < N; i++) {
2670            final ResolveInfo info = resolvers.get(i);
2671
2672            if (info.serviceInfo == null) {
2673                continue;
2674            }
2675
2676            final String packageName = info.serviceInfo.packageName;
2677            if (!possiblePackages.contains(packageName)) {
2678                if (DEBUG_EPHEMERAL) {
2679                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2680                            + " pkg: " + packageName + ", info:" + info);
2681                }
2682                continue;
2683            }
2684
2685            if (DEBUG_EPHEMERAL) {
2686                Slog.v(TAG, "Ephemeral resolver found;"
2687                        + " pkg: " + packageName + ", info:" + info);
2688            }
2689            return new ComponentName(packageName, info.serviceInfo.name);
2690        }
2691        if (DEBUG_EPHEMERAL) {
2692            Slog.v(TAG, "Ephemeral resolver NOT found");
2693        }
2694        return null;
2695    }
2696
2697    private @Nullable ComponentName getEphemeralInstallerLPr() {
2698        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2699        intent.addCategory(Intent.CATEGORY_DEFAULT);
2700        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2701
2702        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2703                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2704                UserHandle.USER_SYSTEM);
2705        if (matches.size() == 0) {
2706            return null;
2707        } else if (matches.size() == 1) {
2708            return matches.get(0).getComponentInfo().getComponentName();
2709        } else {
2710            throw new RuntimeException(
2711                    "There must be at most one ephemeral installer; found " + matches);
2712        }
2713    }
2714
2715    private void primeDomainVerificationsLPw(int userId) {
2716        if (DEBUG_DOMAIN_VERIFICATION) {
2717            Slog.d(TAG, "Priming domain verifications in user " + userId);
2718        }
2719
2720        SystemConfig systemConfig = SystemConfig.getInstance();
2721        ArraySet<String> packages = systemConfig.getLinkedApps();
2722        ArraySet<String> domains = new ArraySet<String>();
2723
2724        for (String packageName : packages) {
2725            PackageParser.Package pkg = mPackages.get(packageName);
2726            if (pkg != null) {
2727                if (!pkg.isSystemApp()) {
2728                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2729                    continue;
2730                }
2731
2732                domains.clear();
2733                for (PackageParser.Activity a : pkg.activities) {
2734                    for (ActivityIntentInfo filter : a.intents) {
2735                        if (hasValidDomains(filter)) {
2736                            domains.addAll(filter.getHostsList());
2737                        }
2738                    }
2739                }
2740
2741                if (domains.size() > 0) {
2742                    if (DEBUG_DOMAIN_VERIFICATION) {
2743                        Slog.v(TAG, "      + " + packageName);
2744                    }
2745                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2746                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2747                    // and then 'always' in the per-user state actually used for intent resolution.
2748                    final IntentFilterVerificationInfo ivi;
2749                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2750                            new ArrayList<String>(domains));
2751                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2752                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2753                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2754                } else {
2755                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2756                            + "' does not handle web links");
2757                }
2758            } else {
2759                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2760            }
2761        }
2762
2763        scheduleWritePackageRestrictionsLocked(userId);
2764        scheduleWriteSettingsLocked();
2765    }
2766
2767    private void applyFactoryDefaultBrowserLPw(int userId) {
2768        // The default browser app's package name is stored in a string resource,
2769        // with a product-specific overlay used for vendor customization.
2770        String browserPkg = mContext.getResources().getString(
2771                com.android.internal.R.string.default_browser);
2772        if (!TextUtils.isEmpty(browserPkg)) {
2773            // non-empty string => required to be a known package
2774            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2775            if (ps == null) {
2776                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2777                browserPkg = null;
2778            } else {
2779                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2780            }
2781        }
2782
2783        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2784        // default.  If there's more than one, just leave everything alone.
2785        if (browserPkg == null) {
2786            calculateDefaultBrowserLPw(userId);
2787        }
2788    }
2789
2790    private void calculateDefaultBrowserLPw(int userId) {
2791        List<String> allBrowsers = resolveAllBrowserApps(userId);
2792        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2793        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2794    }
2795
2796    private List<String> resolveAllBrowserApps(int userId) {
2797        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2798        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2799                PackageManager.MATCH_ALL, userId);
2800
2801        final int count = list.size();
2802        List<String> result = new ArrayList<String>(count);
2803        for (int i=0; i<count; i++) {
2804            ResolveInfo info = list.get(i);
2805            if (info.activityInfo == null
2806                    || !info.handleAllWebDataURI
2807                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2808                    || result.contains(info.activityInfo.packageName)) {
2809                continue;
2810            }
2811            result.add(info.activityInfo.packageName);
2812        }
2813
2814        return result;
2815    }
2816
2817    private boolean packageIsBrowser(String packageName, int userId) {
2818        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2819                PackageManager.MATCH_ALL, userId);
2820        final int N = list.size();
2821        for (int i = 0; i < N; i++) {
2822            ResolveInfo info = list.get(i);
2823            if (packageName.equals(info.activityInfo.packageName)) {
2824                return true;
2825            }
2826        }
2827        return false;
2828    }
2829
2830    private void checkDefaultBrowser() {
2831        final int myUserId = UserHandle.myUserId();
2832        final String packageName = getDefaultBrowserPackageName(myUserId);
2833        if (packageName != null) {
2834            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2835            if (info == null) {
2836                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2837                synchronized (mPackages) {
2838                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2839                }
2840            }
2841        }
2842    }
2843
2844    @Override
2845    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2846            throws RemoteException {
2847        try {
2848            return super.onTransact(code, data, reply, flags);
2849        } catch (RuntimeException e) {
2850            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2851                Slog.wtf(TAG, "Package Manager Crash", e);
2852            }
2853            throw e;
2854        }
2855    }
2856
2857    void cleanupInstallFailedPackage(PackageSetting ps) {
2858        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2859
2860        removeDataDirsLI(ps.volumeUuid, ps.name);
2861        if (ps.codePath != null) {
2862            removeCodePathLI(ps.codePath);
2863        }
2864        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2865            if (ps.resourcePath.isDirectory()) {
2866                FileUtils.deleteContents(ps.resourcePath);
2867            }
2868            ps.resourcePath.delete();
2869        }
2870        mSettings.removePackageLPw(ps.name);
2871    }
2872
2873    static int[] appendInts(int[] cur, int[] add) {
2874        if (add == null) return cur;
2875        if (cur == null) return add;
2876        final int N = add.length;
2877        for (int i=0; i<N; i++) {
2878            cur = appendInt(cur, add[i]);
2879        }
2880        return cur;
2881    }
2882
2883    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2884        if (!sUserManager.exists(userId)) return null;
2885        final PackageSetting ps = (PackageSetting) p.mExtras;
2886        if (ps == null) {
2887            return null;
2888        }
2889
2890        final PermissionsState permissionsState = ps.getPermissionsState();
2891
2892        final int[] gids = permissionsState.computeGids(userId);
2893        final Set<String> permissions = permissionsState.getPermissions(userId);
2894        final PackageUserState state = ps.readUserState(userId);
2895
2896        return PackageParser.generatePackageInfo(p, gids, flags,
2897                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2898    }
2899
2900    @Override
2901    public void checkPackageStartable(String packageName, int userId) {
2902        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2903
2904        synchronized (mPackages) {
2905            final PackageSetting ps = mSettings.mPackages.get(packageName);
2906            if (ps == null) {
2907                throw new SecurityException("Package " + packageName + " was not found!");
2908            }
2909
2910            if (!ps.getInstalled(userId)) {
2911                throw new SecurityException(
2912                        "Package " + packageName + " was not installed for user " + userId + "!");
2913            }
2914
2915            if (mSafeMode && !ps.isSystem()) {
2916                throw new SecurityException("Package " + packageName + " not a system app!");
2917            }
2918
2919            if (ps.frozen) {
2920                throw new SecurityException("Package " + packageName + " is currently frozen!");
2921            }
2922
2923            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
2924                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
2925                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2926            }
2927        }
2928    }
2929
2930    @Override
2931    public boolean isPackageAvailable(String packageName, int userId) {
2932        if (!sUserManager.exists(userId)) return false;
2933        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2934                false /* requireFullPermission */, false /* checkShell */, "is package available");
2935        synchronized (mPackages) {
2936            PackageParser.Package p = mPackages.get(packageName);
2937            if (p != null) {
2938                final PackageSetting ps = (PackageSetting) p.mExtras;
2939                if (ps != null) {
2940                    final PackageUserState state = ps.readUserState(userId);
2941                    if (state != null) {
2942                        return PackageParser.isAvailable(state);
2943                    }
2944                }
2945            }
2946        }
2947        return false;
2948    }
2949
2950    @Override
2951    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2952        if (!sUserManager.exists(userId)) return null;
2953        flags = updateFlagsForPackage(flags, userId, packageName);
2954        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2955                false /* requireFullPermission */, false /* checkShell */, "get package info");
2956        // reader
2957        synchronized (mPackages) {
2958            PackageParser.Package p = mPackages.get(packageName);
2959            if (DEBUG_PACKAGE_INFO)
2960                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2961            if (p != null) {
2962                return generatePackageInfo(p, flags, userId);
2963            }
2964            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2965                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2966            }
2967        }
2968        return null;
2969    }
2970
2971    @Override
2972    public String[] currentToCanonicalPackageNames(String[] names) {
2973        String[] out = new String[names.length];
2974        // reader
2975        synchronized (mPackages) {
2976            for (int i=names.length-1; i>=0; i--) {
2977                PackageSetting ps = mSettings.mPackages.get(names[i]);
2978                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2979            }
2980        }
2981        return out;
2982    }
2983
2984    @Override
2985    public String[] canonicalToCurrentPackageNames(String[] names) {
2986        String[] out = new String[names.length];
2987        // reader
2988        synchronized (mPackages) {
2989            for (int i=names.length-1; i>=0; i--) {
2990                String cur = mSettings.mRenamedPackages.get(names[i]);
2991                out[i] = cur != null ? cur : names[i];
2992            }
2993        }
2994        return out;
2995    }
2996
2997    @Override
2998    public int getPackageUid(String packageName, int flags, int userId) {
2999        if (!sUserManager.exists(userId)) return -1;
3000        flags = updateFlagsForPackage(flags, userId, packageName);
3001        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3002                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3003
3004        // reader
3005        synchronized (mPackages) {
3006            final PackageParser.Package p = mPackages.get(packageName);
3007            if (p != null && p.isMatch(flags)) {
3008                return UserHandle.getUid(userId, p.applicationInfo.uid);
3009            }
3010            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3011                final PackageSetting ps = mSettings.mPackages.get(packageName);
3012                if (ps != null && ps.isMatch(flags)) {
3013                    return UserHandle.getUid(userId, ps.appId);
3014                }
3015            }
3016        }
3017
3018        return -1;
3019    }
3020
3021    @Override
3022    public int[] getPackageGids(String packageName, int flags, int userId) {
3023        if (!sUserManager.exists(userId)) return null;
3024        flags = updateFlagsForPackage(flags, userId, packageName);
3025        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3026                false /* requireFullPermission */, false /* checkShell */,
3027                "getPackageGids");
3028
3029        // reader
3030        synchronized (mPackages) {
3031            final PackageParser.Package p = mPackages.get(packageName);
3032            if (p != null && p.isMatch(flags)) {
3033                PackageSetting ps = (PackageSetting) p.mExtras;
3034                return ps.getPermissionsState().computeGids(userId);
3035            }
3036            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3037                final PackageSetting ps = mSettings.mPackages.get(packageName);
3038                if (ps != null && ps.isMatch(flags)) {
3039                    return ps.getPermissionsState().computeGids(userId);
3040                }
3041            }
3042        }
3043
3044        return null;
3045    }
3046
3047    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3048        if (bp.perm != null) {
3049            return PackageParser.generatePermissionInfo(bp.perm, flags);
3050        }
3051        PermissionInfo pi = new PermissionInfo();
3052        pi.name = bp.name;
3053        pi.packageName = bp.sourcePackage;
3054        pi.nonLocalizedLabel = bp.name;
3055        pi.protectionLevel = bp.protectionLevel;
3056        return pi;
3057    }
3058
3059    @Override
3060    public PermissionInfo getPermissionInfo(String name, int flags) {
3061        // reader
3062        synchronized (mPackages) {
3063            final BasePermission p = mSettings.mPermissions.get(name);
3064            if (p != null) {
3065                return generatePermissionInfo(p, flags);
3066            }
3067            return null;
3068        }
3069    }
3070
3071    @Override
3072    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3073            int flags) {
3074        // reader
3075        synchronized (mPackages) {
3076            if (group != null && !mPermissionGroups.containsKey(group)) {
3077                // This is thrown as NameNotFoundException
3078                return null;
3079            }
3080
3081            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3082            for (BasePermission p : mSettings.mPermissions.values()) {
3083                if (group == null) {
3084                    if (p.perm == null || p.perm.info.group == null) {
3085                        out.add(generatePermissionInfo(p, flags));
3086                    }
3087                } else {
3088                    if (p.perm != null && group.equals(p.perm.info.group)) {
3089                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3090                    }
3091                }
3092            }
3093            return new ParceledListSlice<>(out);
3094        }
3095    }
3096
3097    @Override
3098    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3099        // reader
3100        synchronized (mPackages) {
3101            return PackageParser.generatePermissionGroupInfo(
3102                    mPermissionGroups.get(name), flags);
3103        }
3104    }
3105
3106    @Override
3107    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3108        // reader
3109        synchronized (mPackages) {
3110            final int N = mPermissionGroups.size();
3111            ArrayList<PermissionGroupInfo> out
3112                    = new ArrayList<PermissionGroupInfo>(N);
3113            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3114                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3115            }
3116            return new ParceledListSlice<>(out);
3117        }
3118    }
3119
3120    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3121            int userId) {
3122        if (!sUserManager.exists(userId)) return null;
3123        PackageSetting ps = mSettings.mPackages.get(packageName);
3124        if (ps != null) {
3125            if (ps.pkg == null) {
3126                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3127                        flags, userId);
3128                if (pInfo != null) {
3129                    return pInfo.applicationInfo;
3130                }
3131                return null;
3132            }
3133            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3134                    ps.readUserState(userId), userId);
3135        }
3136        return null;
3137    }
3138
3139    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3140            int userId) {
3141        if (!sUserManager.exists(userId)) return null;
3142        PackageSetting ps = mSettings.mPackages.get(packageName);
3143        if (ps != null) {
3144            PackageParser.Package pkg = ps.pkg;
3145            if (pkg == null) {
3146                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3147                    return null;
3148                }
3149                // Only data remains, so we aren't worried about code paths
3150                pkg = new PackageParser.Package(packageName);
3151                pkg.applicationInfo.packageName = packageName;
3152                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3153                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3154                pkg.applicationInfo.uid = ps.appId;
3155                pkg.applicationInfo.initForUser(userId);
3156                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3157                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3158            }
3159            return generatePackageInfo(pkg, flags, userId);
3160        }
3161        return null;
3162    }
3163
3164    @Override
3165    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3166        if (!sUserManager.exists(userId)) return null;
3167        flags = updateFlagsForApplication(flags, userId, packageName);
3168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3169                false /* requireFullPermission */, false /* checkShell */, "get application info");
3170        // writer
3171        synchronized (mPackages) {
3172            PackageParser.Package p = mPackages.get(packageName);
3173            if (DEBUG_PACKAGE_INFO) Log.v(
3174                    TAG, "getApplicationInfo " + packageName
3175                    + ": " + p);
3176            if (p != null) {
3177                PackageSetting ps = mSettings.mPackages.get(packageName);
3178                if (ps == null) return null;
3179                // Note: isEnabledLP() does not apply here - always return info
3180                return PackageParser.generateApplicationInfo(
3181                        p, flags, ps.readUserState(userId), userId);
3182            }
3183            if ("android".equals(packageName)||"system".equals(packageName)) {
3184                return mAndroidApplication;
3185            }
3186            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3187                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3188            }
3189        }
3190        return null;
3191    }
3192
3193    @Override
3194    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3195            final IPackageDataObserver observer) {
3196        mContext.enforceCallingOrSelfPermission(
3197                android.Manifest.permission.CLEAR_APP_CACHE, null);
3198        // Queue up an async operation since clearing cache may take a little while.
3199        mHandler.post(new Runnable() {
3200            public void run() {
3201                mHandler.removeCallbacks(this);
3202                boolean success = true;
3203                synchronized (mInstallLock) {
3204                    try {
3205                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3206                    } catch (InstallerException e) {
3207                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3208                        success = false;
3209                    }
3210                }
3211                if (observer != null) {
3212                    try {
3213                        observer.onRemoveCompleted(null, success);
3214                    } catch (RemoteException e) {
3215                        Slog.w(TAG, "RemoveException when invoking call back");
3216                    }
3217                }
3218            }
3219        });
3220    }
3221
3222    @Override
3223    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3224            final IntentSender pi) {
3225        mContext.enforceCallingOrSelfPermission(
3226                android.Manifest.permission.CLEAR_APP_CACHE, null);
3227        // Queue up an async operation since clearing cache may take a little while.
3228        mHandler.post(new Runnable() {
3229            public void run() {
3230                mHandler.removeCallbacks(this);
3231                boolean success = true;
3232                synchronized (mInstallLock) {
3233                    try {
3234                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3235                    } catch (InstallerException e) {
3236                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3237                        success = false;
3238                    }
3239                }
3240                if(pi != null) {
3241                    try {
3242                        // Callback via pending intent
3243                        int code = success ? 1 : 0;
3244                        pi.sendIntent(null, code, null,
3245                                null, null);
3246                    } catch (SendIntentException e1) {
3247                        Slog.i(TAG, "Failed to send pending intent");
3248                    }
3249                }
3250            }
3251        });
3252    }
3253
3254    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3255        synchronized (mInstallLock) {
3256            try {
3257                mInstaller.freeCache(volumeUuid, freeStorageSize);
3258            } catch (InstallerException e) {
3259                throw new IOException("Failed to free enough space", e);
3260            }
3261        }
3262    }
3263
3264    /**
3265     * Return if the user key is currently unlocked.
3266     */
3267    private boolean isUserKeyUnlocked(int userId) {
3268        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3269            final IMountService mount = IMountService.Stub
3270                    .asInterface(ServiceManager.getService("mount"));
3271            if (mount == null) {
3272                Slog.w(TAG, "Early during boot, assuming locked");
3273                return false;
3274            }
3275            final long token = Binder.clearCallingIdentity();
3276            try {
3277                return mount.isUserKeyUnlocked(userId);
3278            } catch (RemoteException e) {
3279                throw e.rethrowAsRuntimeException();
3280            } finally {
3281                Binder.restoreCallingIdentity(token);
3282            }
3283        } else {
3284            return true;
3285        }
3286    }
3287
3288    /**
3289     * Update given flags based on encryption status of current user.
3290     */
3291    private int updateFlags(int flags, int userId) {
3292        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3293                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3294            // Caller expressed an explicit opinion about what encryption
3295            // aware/unaware components they want to see, so fall through and
3296            // give them what they want
3297        } else {
3298            // Caller expressed no opinion, so match based on user state
3299            if (isUserKeyUnlocked(userId)) {
3300                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3301            } else {
3302                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3303            }
3304        }
3305        return flags;
3306    }
3307
3308    /**
3309     * Update given flags when being used to request {@link PackageInfo}.
3310     */
3311    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3312        boolean triaged = true;
3313        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3314                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3315            // Caller is asking for component details, so they'd better be
3316            // asking for specific encryption matching behavior, or be triaged
3317            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3318                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3319                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3320                triaged = false;
3321            }
3322        }
3323        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3324                | PackageManager.MATCH_SYSTEM_ONLY
3325                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3326            triaged = false;
3327        }
3328        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3329            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3330                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3331        }
3332        return updateFlags(flags, userId);
3333    }
3334
3335    /**
3336     * Update given flags when being used to request {@link ApplicationInfo}.
3337     */
3338    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3339        return updateFlagsForPackage(flags, userId, cookie);
3340    }
3341
3342    /**
3343     * Update given flags when being used to request {@link ComponentInfo}.
3344     */
3345    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3346        if (cookie instanceof Intent) {
3347            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3348                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3349            }
3350        }
3351
3352        boolean triaged = true;
3353        // Caller is asking for component details, so they'd better be
3354        // asking for specific encryption matching behavior, or be triaged
3355        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3356                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3357                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3358            triaged = false;
3359        }
3360        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3361            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3362                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3363        }
3364
3365        return updateFlags(flags, userId);
3366    }
3367
3368    /**
3369     * Update given flags when being used to request {@link ResolveInfo}.
3370     */
3371    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3372        // Safe mode means we shouldn't match any third-party components
3373        if (mSafeMode) {
3374            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3375        }
3376
3377        return updateFlagsForComponent(flags, userId, cookie);
3378    }
3379
3380    @Override
3381    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3382        if (!sUserManager.exists(userId)) return null;
3383        flags = updateFlagsForComponent(flags, userId, component);
3384        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3385                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3386        synchronized (mPackages) {
3387            PackageParser.Activity a = mActivities.mActivities.get(component);
3388
3389            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3390            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3391                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3392                if (ps == null) return null;
3393                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3394                        userId);
3395            }
3396            if (mResolveComponentName.equals(component)) {
3397                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3398                        new PackageUserState(), userId);
3399            }
3400        }
3401        return null;
3402    }
3403
3404    @Override
3405    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3406            String resolvedType) {
3407        synchronized (mPackages) {
3408            if (component.equals(mResolveComponentName)) {
3409                // The resolver supports EVERYTHING!
3410                return true;
3411            }
3412            PackageParser.Activity a = mActivities.mActivities.get(component);
3413            if (a == null) {
3414                return false;
3415            }
3416            for (int i=0; i<a.intents.size(); i++) {
3417                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3418                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3419                    return true;
3420                }
3421            }
3422            return false;
3423        }
3424    }
3425
3426    @Override
3427    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3428        if (!sUserManager.exists(userId)) return null;
3429        flags = updateFlagsForComponent(flags, userId, component);
3430        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3431                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3432        synchronized (mPackages) {
3433            PackageParser.Activity a = mReceivers.mActivities.get(component);
3434            if (DEBUG_PACKAGE_INFO) Log.v(
3435                TAG, "getReceiverInfo " + component + ": " + a);
3436            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3437                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3438                if (ps == null) return null;
3439                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3440                        userId);
3441            }
3442        }
3443        return null;
3444    }
3445
3446    @Override
3447    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3448        if (!sUserManager.exists(userId)) return null;
3449        flags = updateFlagsForComponent(flags, userId, component);
3450        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3451                false /* requireFullPermission */, false /* checkShell */, "get service info");
3452        synchronized (mPackages) {
3453            PackageParser.Service s = mServices.mServices.get(component);
3454            if (DEBUG_PACKAGE_INFO) Log.v(
3455                TAG, "getServiceInfo " + component + ": " + s);
3456            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3457                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3458                if (ps == null) return null;
3459                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3460                        userId);
3461            }
3462        }
3463        return null;
3464    }
3465
3466    @Override
3467    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3468        if (!sUserManager.exists(userId)) return null;
3469        flags = updateFlagsForComponent(flags, userId, component);
3470        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3471                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3472        synchronized (mPackages) {
3473            PackageParser.Provider p = mProviders.mProviders.get(component);
3474            if (DEBUG_PACKAGE_INFO) Log.v(
3475                TAG, "getProviderInfo " + component + ": " + p);
3476            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3477                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3478                if (ps == null) return null;
3479                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3480                        userId);
3481            }
3482        }
3483        return null;
3484    }
3485
3486    @Override
3487    public String[] getSystemSharedLibraryNames() {
3488        Set<String> libSet;
3489        synchronized (mPackages) {
3490            libSet = mSharedLibraries.keySet();
3491            int size = libSet.size();
3492            if (size > 0) {
3493                String[] libs = new String[size];
3494                libSet.toArray(libs);
3495                return libs;
3496            }
3497        }
3498        return null;
3499    }
3500
3501    @Override
3502    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3503        synchronized (mPackages) {
3504            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3505                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3506            if (libraryEntry != null) {
3507                return libraryEntry.apk;
3508            }
3509        }
3510        return null;
3511    }
3512
3513    @Override
3514    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3515        synchronized (mPackages) {
3516            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3517
3518            final FeatureInfo fi = new FeatureInfo();
3519            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3520                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3521            res.add(fi);
3522
3523            return new ParceledListSlice<>(res);
3524        }
3525    }
3526
3527    @Override
3528    public boolean hasSystemFeature(String name, int version) {
3529        synchronized (mPackages) {
3530            final FeatureInfo feat = mAvailableFeatures.get(name);
3531            if (feat == null) {
3532                return false;
3533            } else {
3534                return feat.version >= version;
3535            }
3536        }
3537    }
3538
3539    @Override
3540    public int checkPermission(String permName, String pkgName, int userId) {
3541        if (!sUserManager.exists(userId)) {
3542            return PackageManager.PERMISSION_DENIED;
3543        }
3544
3545        synchronized (mPackages) {
3546            final PackageParser.Package p = mPackages.get(pkgName);
3547            if (p != null && p.mExtras != null) {
3548                final PackageSetting ps = (PackageSetting) p.mExtras;
3549                final PermissionsState permissionsState = ps.getPermissionsState();
3550                if (permissionsState.hasPermission(permName, userId)) {
3551                    return PackageManager.PERMISSION_GRANTED;
3552                }
3553                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3554                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3555                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3556                    return PackageManager.PERMISSION_GRANTED;
3557                }
3558            }
3559        }
3560
3561        return PackageManager.PERMISSION_DENIED;
3562    }
3563
3564    @Override
3565    public int checkUidPermission(String permName, int uid) {
3566        final int userId = UserHandle.getUserId(uid);
3567
3568        if (!sUserManager.exists(userId)) {
3569            return PackageManager.PERMISSION_DENIED;
3570        }
3571
3572        synchronized (mPackages) {
3573            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3574            if (obj != null) {
3575                final SettingBase ps = (SettingBase) obj;
3576                final PermissionsState permissionsState = ps.getPermissionsState();
3577                if (permissionsState.hasPermission(permName, userId)) {
3578                    return PackageManager.PERMISSION_GRANTED;
3579                }
3580                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3581                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3582                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3583                    return PackageManager.PERMISSION_GRANTED;
3584                }
3585            } else {
3586                ArraySet<String> perms = mSystemPermissions.get(uid);
3587                if (perms != null) {
3588                    if (perms.contains(permName)) {
3589                        return PackageManager.PERMISSION_GRANTED;
3590                    }
3591                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3592                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3593                        return PackageManager.PERMISSION_GRANTED;
3594                    }
3595                }
3596            }
3597        }
3598
3599        return PackageManager.PERMISSION_DENIED;
3600    }
3601
3602    @Override
3603    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3604        if (UserHandle.getCallingUserId() != userId) {
3605            mContext.enforceCallingPermission(
3606                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3607                    "isPermissionRevokedByPolicy for user " + userId);
3608        }
3609
3610        if (checkPermission(permission, packageName, userId)
3611                == PackageManager.PERMISSION_GRANTED) {
3612            return false;
3613        }
3614
3615        final long identity = Binder.clearCallingIdentity();
3616        try {
3617            final int flags = getPermissionFlags(permission, packageName, userId);
3618            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3619        } finally {
3620            Binder.restoreCallingIdentity(identity);
3621        }
3622    }
3623
3624    @Override
3625    public String getPermissionControllerPackageName() {
3626        synchronized (mPackages) {
3627            return mRequiredInstallerPackage;
3628        }
3629    }
3630
3631    /**
3632     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3633     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3634     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3635     * @param message the message to log on security exception
3636     */
3637    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3638            boolean checkShell, String message) {
3639        if (userId < 0) {
3640            throw new IllegalArgumentException("Invalid userId " + userId);
3641        }
3642        if (checkShell) {
3643            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3644        }
3645        if (userId == UserHandle.getUserId(callingUid)) return;
3646        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3647            if (requireFullPermission) {
3648                mContext.enforceCallingOrSelfPermission(
3649                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3650            } else {
3651                try {
3652                    mContext.enforceCallingOrSelfPermission(
3653                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3654                } catch (SecurityException se) {
3655                    mContext.enforceCallingOrSelfPermission(
3656                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3657                }
3658            }
3659        }
3660    }
3661
3662    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3663        if (callingUid == Process.SHELL_UID) {
3664            if (userHandle >= 0
3665                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3666                throw new SecurityException("Shell does not have permission to access user "
3667                        + userHandle);
3668            } else if (userHandle < 0) {
3669                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3670                        + Debug.getCallers(3));
3671            }
3672        }
3673    }
3674
3675    private BasePermission findPermissionTreeLP(String permName) {
3676        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3677            if (permName.startsWith(bp.name) &&
3678                    permName.length() > bp.name.length() &&
3679                    permName.charAt(bp.name.length()) == '.') {
3680                return bp;
3681            }
3682        }
3683        return null;
3684    }
3685
3686    private BasePermission checkPermissionTreeLP(String permName) {
3687        if (permName != null) {
3688            BasePermission bp = findPermissionTreeLP(permName);
3689            if (bp != null) {
3690                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3691                    return bp;
3692                }
3693                throw new SecurityException("Calling uid "
3694                        + Binder.getCallingUid()
3695                        + " is not allowed to add to permission tree "
3696                        + bp.name + " owned by uid " + bp.uid);
3697            }
3698        }
3699        throw new SecurityException("No permission tree found for " + permName);
3700    }
3701
3702    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3703        if (s1 == null) {
3704            return s2 == null;
3705        }
3706        if (s2 == null) {
3707            return false;
3708        }
3709        if (s1.getClass() != s2.getClass()) {
3710            return false;
3711        }
3712        return s1.equals(s2);
3713    }
3714
3715    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3716        if (pi1.icon != pi2.icon) return false;
3717        if (pi1.logo != pi2.logo) return false;
3718        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3719        if (!compareStrings(pi1.name, pi2.name)) return false;
3720        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3721        // We'll take care of setting this one.
3722        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3723        // These are not currently stored in settings.
3724        //if (!compareStrings(pi1.group, pi2.group)) return false;
3725        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3726        //if (pi1.labelRes != pi2.labelRes) return false;
3727        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3728        return true;
3729    }
3730
3731    int permissionInfoFootprint(PermissionInfo info) {
3732        int size = info.name.length();
3733        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3734        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3735        return size;
3736    }
3737
3738    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3739        int size = 0;
3740        for (BasePermission perm : mSettings.mPermissions.values()) {
3741            if (perm.uid == tree.uid) {
3742                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3743            }
3744        }
3745        return size;
3746    }
3747
3748    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3749        // We calculate the max size of permissions defined by this uid and throw
3750        // if that plus the size of 'info' would exceed our stated maximum.
3751        if (tree.uid != Process.SYSTEM_UID) {
3752            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3753            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3754                throw new SecurityException("Permission tree size cap exceeded");
3755            }
3756        }
3757    }
3758
3759    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3760        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3761            throw new SecurityException("Label must be specified in permission");
3762        }
3763        BasePermission tree = checkPermissionTreeLP(info.name);
3764        BasePermission bp = mSettings.mPermissions.get(info.name);
3765        boolean added = bp == null;
3766        boolean changed = true;
3767        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3768        if (added) {
3769            enforcePermissionCapLocked(info, tree);
3770            bp = new BasePermission(info.name, tree.sourcePackage,
3771                    BasePermission.TYPE_DYNAMIC);
3772        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3773            throw new SecurityException(
3774                    "Not allowed to modify non-dynamic permission "
3775                    + info.name);
3776        } else {
3777            if (bp.protectionLevel == fixedLevel
3778                    && bp.perm.owner.equals(tree.perm.owner)
3779                    && bp.uid == tree.uid
3780                    && comparePermissionInfos(bp.perm.info, info)) {
3781                changed = false;
3782            }
3783        }
3784        bp.protectionLevel = fixedLevel;
3785        info = new PermissionInfo(info);
3786        info.protectionLevel = fixedLevel;
3787        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3788        bp.perm.info.packageName = tree.perm.info.packageName;
3789        bp.uid = tree.uid;
3790        if (added) {
3791            mSettings.mPermissions.put(info.name, bp);
3792        }
3793        if (changed) {
3794            if (!async) {
3795                mSettings.writeLPr();
3796            } else {
3797                scheduleWriteSettingsLocked();
3798            }
3799        }
3800        return added;
3801    }
3802
3803    @Override
3804    public boolean addPermission(PermissionInfo info) {
3805        synchronized (mPackages) {
3806            return addPermissionLocked(info, false);
3807        }
3808    }
3809
3810    @Override
3811    public boolean addPermissionAsync(PermissionInfo info) {
3812        synchronized (mPackages) {
3813            return addPermissionLocked(info, true);
3814        }
3815    }
3816
3817    @Override
3818    public void removePermission(String name) {
3819        synchronized (mPackages) {
3820            checkPermissionTreeLP(name);
3821            BasePermission bp = mSettings.mPermissions.get(name);
3822            if (bp != null) {
3823                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3824                    throw new SecurityException(
3825                            "Not allowed to modify non-dynamic permission "
3826                            + name);
3827                }
3828                mSettings.mPermissions.remove(name);
3829                mSettings.writeLPr();
3830            }
3831        }
3832    }
3833
3834    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3835            BasePermission bp) {
3836        int index = pkg.requestedPermissions.indexOf(bp.name);
3837        if (index == -1) {
3838            throw new SecurityException("Package " + pkg.packageName
3839                    + " has not requested permission " + bp.name);
3840        }
3841        if (!bp.isRuntime() && !bp.isDevelopment()) {
3842            throw new SecurityException("Permission " + bp.name
3843                    + " is not a changeable permission type");
3844        }
3845    }
3846
3847    @Override
3848    public void grantRuntimePermission(String packageName, String name, final int userId) {
3849        if (!sUserManager.exists(userId)) {
3850            Log.e(TAG, "No such user:" + userId);
3851            return;
3852        }
3853
3854        mContext.enforceCallingOrSelfPermission(
3855                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3856                "grantRuntimePermission");
3857
3858        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3859                true /* requireFullPermission */, true /* checkShell */,
3860                "grantRuntimePermission");
3861
3862        final int uid;
3863        final SettingBase sb;
3864
3865        synchronized (mPackages) {
3866            final PackageParser.Package pkg = mPackages.get(packageName);
3867            if (pkg == null) {
3868                throw new IllegalArgumentException("Unknown package: " + packageName);
3869            }
3870
3871            final BasePermission bp = mSettings.mPermissions.get(name);
3872            if (bp == null) {
3873                throw new IllegalArgumentException("Unknown permission: " + name);
3874            }
3875
3876            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3877
3878            // If a permission review is required for legacy apps we represent
3879            // their permissions as always granted runtime ones since we need
3880            // to keep the review required permission flag per user while an
3881            // install permission's state is shared across all users.
3882            if (Build.PERMISSIONS_REVIEW_REQUIRED
3883                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3884                    && bp.isRuntime()) {
3885                return;
3886            }
3887
3888            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3889            sb = (SettingBase) pkg.mExtras;
3890            if (sb == null) {
3891                throw new IllegalArgumentException("Unknown package: " + packageName);
3892            }
3893
3894            final PermissionsState permissionsState = sb.getPermissionsState();
3895
3896            final int flags = permissionsState.getPermissionFlags(name, userId);
3897            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3898                throw new SecurityException("Cannot grant system fixed permission "
3899                        + name + " for package " + packageName);
3900            }
3901
3902            if (bp.isDevelopment()) {
3903                // Development permissions must be handled specially, since they are not
3904                // normal runtime permissions.  For now they apply to all users.
3905                if (permissionsState.grantInstallPermission(bp) !=
3906                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3907                    scheduleWriteSettingsLocked();
3908                }
3909                return;
3910            }
3911
3912            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3913                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3914                return;
3915            }
3916
3917            final int result = permissionsState.grantRuntimePermission(bp, userId);
3918            switch (result) {
3919                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3920                    return;
3921                }
3922
3923                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3924                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3925                    mHandler.post(new Runnable() {
3926                        @Override
3927                        public void run() {
3928                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3929                        }
3930                    });
3931                }
3932                break;
3933            }
3934
3935            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3936
3937            // Not critical if that is lost - app has to request again.
3938            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3939        }
3940
3941        // Only need to do this if user is initialized. Otherwise it's a new user
3942        // and there are no processes running as the user yet and there's no need
3943        // to make an expensive call to remount processes for the changed permissions.
3944        if (READ_EXTERNAL_STORAGE.equals(name)
3945                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3946            final long token = Binder.clearCallingIdentity();
3947            try {
3948                if (sUserManager.isInitialized(userId)) {
3949                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3950                            MountServiceInternal.class);
3951                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3952                }
3953            } finally {
3954                Binder.restoreCallingIdentity(token);
3955            }
3956        }
3957    }
3958
3959    @Override
3960    public void revokeRuntimePermission(String packageName, String name, int userId) {
3961        if (!sUserManager.exists(userId)) {
3962            Log.e(TAG, "No such user:" + userId);
3963            return;
3964        }
3965
3966        mContext.enforceCallingOrSelfPermission(
3967                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3968                "revokeRuntimePermission");
3969
3970        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3971                true /* requireFullPermission */, true /* checkShell */,
3972                "revokeRuntimePermission");
3973
3974        final int appId;
3975
3976        synchronized (mPackages) {
3977            final PackageParser.Package pkg = mPackages.get(packageName);
3978            if (pkg == null) {
3979                throw new IllegalArgumentException("Unknown package: " + packageName);
3980            }
3981
3982            final BasePermission bp = mSettings.mPermissions.get(name);
3983            if (bp == null) {
3984                throw new IllegalArgumentException("Unknown permission: " + name);
3985            }
3986
3987            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3988
3989            // If a permission review is required for legacy apps we represent
3990            // their permissions as always granted runtime ones since we need
3991            // to keep the review required permission flag per user while an
3992            // install permission's state is shared across all users.
3993            if (Build.PERMISSIONS_REVIEW_REQUIRED
3994                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3995                    && bp.isRuntime()) {
3996                return;
3997            }
3998
3999            SettingBase sb = (SettingBase) pkg.mExtras;
4000            if (sb == null) {
4001                throw new IllegalArgumentException("Unknown package: " + packageName);
4002            }
4003
4004            final PermissionsState permissionsState = sb.getPermissionsState();
4005
4006            final int flags = permissionsState.getPermissionFlags(name, userId);
4007            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4008                throw new SecurityException("Cannot revoke system fixed permission "
4009                        + name + " for package " + packageName);
4010            }
4011
4012            if (bp.isDevelopment()) {
4013                // Development permissions must be handled specially, since they are not
4014                // normal runtime permissions.  For now they apply to all users.
4015                if (permissionsState.revokeInstallPermission(bp) !=
4016                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4017                    scheduleWriteSettingsLocked();
4018                }
4019                return;
4020            }
4021
4022            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4023                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4024                return;
4025            }
4026
4027            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4028
4029            // Critical, after this call app should never have the permission.
4030            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4031
4032            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4033        }
4034
4035        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4036    }
4037
4038    @Override
4039    public void resetRuntimePermissions() {
4040        mContext.enforceCallingOrSelfPermission(
4041                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4042                "revokeRuntimePermission");
4043
4044        int callingUid = Binder.getCallingUid();
4045        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4046            mContext.enforceCallingOrSelfPermission(
4047                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4048                    "resetRuntimePermissions");
4049        }
4050
4051        synchronized (mPackages) {
4052            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4053            for (int userId : UserManagerService.getInstance().getUserIds()) {
4054                final int packageCount = mPackages.size();
4055                for (int i = 0; i < packageCount; i++) {
4056                    PackageParser.Package pkg = mPackages.valueAt(i);
4057                    if (!(pkg.mExtras instanceof PackageSetting)) {
4058                        continue;
4059                    }
4060                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4061                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4062                }
4063            }
4064        }
4065    }
4066
4067    @Override
4068    public int getPermissionFlags(String name, String packageName, int userId) {
4069        if (!sUserManager.exists(userId)) {
4070            return 0;
4071        }
4072
4073        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4074
4075        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4076                true /* requireFullPermission */, false /* checkShell */,
4077                "getPermissionFlags");
4078
4079        synchronized (mPackages) {
4080            final PackageParser.Package pkg = mPackages.get(packageName);
4081            if (pkg == null) {
4082                throw new IllegalArgumentException("Unknown package: " + packageName);
4083            }
4084
4085            final BasePermission bp = mSettings.mPermissions.get(name);
4086            if (bp == null) {
4087                throw new IllegalArgumentException("Unknown permission: " + name);
4088            }
4089
4090            SettingBase sb = (SettingBase) pkg.mExtras;
4091            if (sb == null) {
4092                throw new IllegalArgumentException("Unknown package: " + packageName);
4093            }
4094
4095            PermissionsState permissionsState = sb.getPermissionsState();
4096            return permissionsState.getPermissionFlags(name, userId);
4097        }
4098    }
4099
4100    @Override
4101    public void updatePermissionFlags(String name, String packageName, int flagMask,
4102            int flagValues, int userId) {
4103        if (!sUserManager.exists(userId)) {
4104            return;
4105        }
4106
4107        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4108
4109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4110                true /* requireFullPermission */, true /* checkShell */,
4111                "updatePermissionFlags");
4112
4113        // Only the system can change these flags and nothing else.
4114        if (getCallingUid() != Process.SYSTEM_UID) {
4115            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4116            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4117            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4118            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4119            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4120        }
4121
4122        synchronized (mPackages) {
4123            final PackageParser.Package pkg = mPackages.get(packageName);
4124            if (pkg == null) {
4125                throw new IllegalArgumentException("Unknown package: " + packageName);
4126            }
4127
4128            final BasePermission bp = mSettings.mPermissions.get(name);
4129            if (bp == null) {
4130                throw new IllegalArgumentException("Unknown permission: " + name);
4131            }
4132
4133            SettingBase sb = (SettingBase) pkg.mExtras;
4134            if (sb == null) {
4135                throw new IllegalArgumentException("Unknown package: " + packageName);
4136            }
4137
4138            PermissionsState permissionsState = sb.getPermissionsState();
4139
4140            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4141
4142            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4143                // Install and runtime permissions are stored in different places,
4144                // so figure out what permission changed and persist the change.
4145                if (permissionsState.getInstallPermissionState(name) != null) {
4146                    scheduleWriteSettingsLocked();
4147                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4148                        || hadState) {
4149                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4150                }
4151            }
4152        }
4153    }
4154
4155    /**
4156     * Update the permission flags for all packages and runtime permissions of a user in order
4157     * to allow device or profile owner to remove POLICY_FIXED.
4158     */
4159    @Override
4160    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4161        if (!sUserManager.exists(userId)) {
4162            return;
4163        }
4164
4165        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4166
4167        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4168                true /* requireFullPermission */, true /* checkShell */,
4169                "updatePermissionFlagsForAllApps");
4170
4171        // Only the system can change system fixed flags.
4172        if (getCallingUid() != Process.SYSTEM_UID) {
4173            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4174            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4175        }
4176
4177        synchronized (mPackages) {
4178            boolean changed = false;
4179            final int packageCount = mPackages.size();
4180            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4181                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4182                SettingBase sb = (SettingBase) pkg.mExtras;
4183                if (sb == null) {
4184                    continue;
4185                }
4186                PermissionsState permissionsState = sb.getPermissionsState();
4187                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4188                        userId, flagMask, flagValues);
4189            }
4190            if (changed) {
4191                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4192            }
4193        }
4194    }
4195
4196    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4197        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4198                != PackageManager.PERMISSION_GRANTED
4199            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4200                != PackageManager.PERMISSION_GRANTED) {
4201            throw new SecurityException(message + " requires "
4202                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4203                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4204        }
4205    }
4206
4207    @Override
4208    public boolean shouldShowRequestPermissionRationale(String permissionName,
4209            String packageName, int userId) {
4210        if (UserHandle.getCallingUserId() != userId) {
4211            mContext.enforceCallingPermission(
4212                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4213                    "canShowRequestPermissionRationale for user " + userId);
4214        }
4215
4216        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4217        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4218            return false;
4219        }
4220
4221        if (checkPermission(permissionName, packageName, userId)
4222                == PackageManager.PERMISSION_GRANTED) {
4223            return false;
4224        }
4225
4226        final int flags;
4227
4228        final long identity = Binder.clearCallingIdentity();
4229        try {
4230            flags = getPermissionFlags(permissionName,
4231                    packageName, userId);
4232        } finally {
4233            Binder.restoreCallingIdentity(identity);
4234        }
4235
4236        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4237                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4238                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4239
4240        if ((flags & fixedFlags) != 0) {
4241            return false;
4242        }
4243
4244        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4245    }
4246
4247    @Override
4248    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4249        mContext.enforceCallingOrSelfPermission(
4250                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4251                "addOnPermissionsChangeListener");
4252
4253        synchronized (mPackages) {
4254            mOnPermissionChangeListeners.addListenerLocked(listener);
4255        }
4256    }
4257
4258    @Override
4259    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4260        synchronized (mPackages) {
4261            mOnPermissionChangeListeners.removeListenerLocked(listener);
4262        }
4263    }
4264
4265    @Override
4266    public boolean isProtectedBroadcast(String actionName) {
4267        synchronized (mPackages) {
4268            if (mProtectedBroadcasts.contains(actionName)) {
4269                return true;
4270            } else if (actionName != null) {
4271                // TODO: remove these terrible hacks
4272                if (actionName.startsWith("android.net.netmon.lingerExpired")
4273                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4274                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4275                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4276                    return true;
4277                }
4278            }
4279        }
4280        return false;
4281    }
4282
4283    @Override
4284    public int checkSignatures(String pkg1, String pkg2) {
4285        synchronized (mPackages) {
4286            final PackageParser.Package p1 = mPackages.get(pkg1);
4287            final PackageParser.Package p2 = mPackages.get(pkg2);
4288            if (p1 == null || p1.mExtras == null
4289                    || p2 == null || p2.mExtras == null) {
4290                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4291            }
4292            return compareSignatures(p1.mSignatures, p2.mSignatures);
4293        }
4294    }
4295
4296    @Override
4297    public int checkUidSignatures(int uid1, int uid2) {
4298        // Map to base uids.
4299        uid1 = UserHandle.getAppId(uid1);
4300        uid2 = UserHandle.getAppId(uid2);
4301        // reader
4302        synchronized (mPackages) {
4303            Signature[] s1;
4304            Signature[] s2;
4305            Object obj = mSettings.getUserIdLPr(uid1);
4306            if (obj != null) {
4307                if (obj instanceof SharedUserSetting) {
4308                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4309                } else if (obj instanceof PackageSetting) {
4310                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4311                } else {
4312                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4313                }
4314            } else {
4315                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4316            }
4317            obj = mSettings.getUserIdLPr(uid2);
4318            if (obj != null) {
4319                if (obj instanceof SharedUserSetting) {
4320                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4321                } else if (obj instanceof PackageSetting) {
4322                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4323                } else {
4324                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4325                }
4326            } else {
4327                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4328            }
4329            return compareSignatures(s1, s2);
4330        }
4331    }
4332
4333    private void killUid(int appId, int userId, String reason) {
4334        final long identity = Binder.clearCallingIdentity();
4335        try {
4336            IActivityManager am = ActivityManagerNative.getDefault();
4337            if (am != null) {
4338                try {
4339                    am.killUid(appId, userId, reason);
4340                } catch (RemoteException e) {
4341                    /* ignore - same process */
4342                }
4343            }
4344        } finally {
4345            Binder.restoreCallingIdentity(identity);
4346        }
4347    }
4348
4349    /**
4350     * Compares two sets of signatures. Returns:
4351     * <br />
4352     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4353     * <br />
4354     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4355     * <br />
4356     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4357     * <br />
4358     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4359     * <br />
4360     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4361     */
4362    static int compareSignatures(Signature[] s1, Signature[] s2) {
4363        if (s1 == null) {
4364            return s2 == null
4365                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4366                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4367        }
4368
4369        if (s2 == null) {
4370            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4371        }
4372
4373        if (s1.length != s2.length) {
4374            return PackageManager.SIGNATURE_NO_MATCH;
4375        }
4376
4377        // Since both signature sets are of size 1, we can compare without HashSets.
4378        if (s1.length == 1) {
4379            return s1[0].equals(s2[0]) ?
4380                    PackageManager.SIGNATURE_MATCH :
4381                    PackageManager.SIGNATURE_NO_MATCH;
4382        }
4383
4384        ArraySet<Signature> set1 = new ArraySet<Signature>();
4385        for (Signature sig : s1) {
4386            set1.add(sig);
4387        }
4388        ArraySet<Signature> set2 = new ArraySet<Signature>();
4389        for (Signature sig : s2) {
4390            set2.add(sig);
4391        }
4392        // Make sure s2 contains all signatures in s1.
4393        if (set1.equals(set2)) {
4394            return PackageManager.SIGNATURE_MATCH;
4395        }
4396        return PackageManager.SIGNATURE_NO_MATCH;
4397    }
4398
4399    /**
4400     * If the database version for this type of package (internal storage or
4401     * external storage) is less than the version where package signatures
4402     * were updated, return true.
4403     */
4404    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4405        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4406        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4407    }
4408
4409    /**
4410     * Used for backward compatibility to make sure any packages with
4411     * certificate chains get upgraded to the new style. {@code existingSigs}
4412     * will be in the old format (since they were stored on disk from before the
4413     * system upgrade) and {@code scannedSigs} will be in the newer format.
4414     */
4415    private int compareSignaturesCompat(PackageSignatures existingSigs,
4416            PackageParser.Package scannedPkg) {
4417        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4418            return PackageManager.SIGNATURE_NO_MATCH;
4419        }
4420
4421        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4422        for (Signature sig : existingSigs.mSignatures) {
4423            existingSet.add(sig);
4424        }
4425        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4426        for (Signature sig : scannedPkg.mSignatures) {
4427            try {
4428                Signature[] chainSignatures = sig.getChainSignatures();
4429                for (Signature chainSig : chainSignatures) {
4430                    scannedCompatSet.add(chainSig);
4431                }
4432            } catch (CertificateEncodingException e) {
4433                scannedCompatSet.add(sig);
4434            }
4435        }
4436        /*
4437         * Make sure the expanded scanned set contains all signatures in the
4438         * existing one.
4439         */
4440        if (scannedCompatSet.equals(existingSet)) {
4441            // Migrate the old signatures to the new scheme.
4442            existingSigs.assignSignatures(scannedPkg.mSignatures);
4443            // The new KeySets will be re-added later in the scanning process.
4444            synchronized (mPackages) {
4445                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4446            }
4447            return PackageManager.SIGNATURE_MATCH;
4448        }
4449        return PackageManager.SIGNATURE_NO_MATCH;
4450    }
4451
4452    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4453        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4454        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4455    }
4456
4457    private int compareSignaturesRecover(PackageSignatures existingSigs,
4458            PackageParser.Package scannedPkg) {
4459        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4460            return PackageManager.SIGNATURE_NO_MATCH;
4461        }
4462
4463        String msg = null;
4464        try {
4465            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4466                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4467                        + scannedPkg.packageName);
4468                return PackageManager.SIGNATURE_MATCH;
4469            }
4470        } catch (CertificateException e) {
4471            msg = e.getMessage();
4472        }
4473
4474        logCriticalInfo(Log.INFO,
4475                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4476        return PackageManager.SIGNATURE_NO_MATCH;
4477    }
4478
4479    @Override
4480    public List<String> getAllPackages() {
4481        synchronized (mPackages) {
4482            return new ArrayList<String>(mPackages.keySet());
4483        }
4484    }
4485
4486    @Override
4487    public String[] getPackagesForUid(int uid) {
4488        uid = UserHandle.getAppId(uid);
4489        // reader
4490        synchronized (mPackages) {
4491            Object obj = mSettings.getUserIdLPr(uid);
4492            if (obj instanceof SharedUserSetting) {
4493                final SharedUserSetting sus = (SharedUserSetting) obj;
4494                final int N = sus.packages.size();
4495                final String[] res = new String[N];
4496                final Iterator<PackageSetting> it = sus.packages.iterator();
4497                int i = 0;
4498                while (it.hasNext()) {
4499                    res[i++] = it.next().name;
4500                }
4501                return res;
4502            } else if (obj instanceof PackageSetting) {
4503                final PackageSetting ps = (PackageSetting) obj;
4504                return new String[] { ps.name };
4505            }
4506        }
4507        return null;
4508    }
4509
4510    @Override
4511    public String getNameForUid(int uid) {
4512        // reader
4513        synchronized (mPackages) {
4514            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4515            if (obj instanceof SharedUserSetting) {
4516                final SharedUserSetting sus = (SharedUserSetting) obj;
4517                return sus.name + ":" + sus.userId;
4518            } else if (obj instanceof PackageSetting) {
4519                final PackageSetting ps = (PackageSetting) obj;
4520                return ps.name;
4521            }
4522        }
4523        return null;
4524    }
4525
4526    @Override
4527    public int getUidForSharedUser(String sharedUserName) {
4528        if(sharedUserName == null) {
4529            return -1;
4530        }
4531        // reader
4532        synchronized (mPackages) {
4533            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4534            if (suid == null) {
4535                return -1;
4536            }
4537            return suid.userId;
4538        }
4539    }
4540
4541    @Override
4542    public int getFlagsForUid(int uid) {
4543        synchronized (mPackages) {
4544            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4545            if (obj instanceof SharedUserSetting) {
4546                final SharedUserSetting sus = (SharedUserSetting) obj;
4547                return sus.pkgFlags;
4548            } else if (obj instanceof PackageSetting) {
4549                final PackageSetting ps = (PackageSetting) obj;
4550                return ps.pkgFlags;
4551            }
4552        }
4553        return 0;
4554    }
4555
4556    @Override
4557    public int getPrivateFlagsForUid(int uid) {
4558        synchronized (mPackages) {
4559            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4560            if (obj instanceof SharedUserSetting) {
4561                final SharedUserSetting sus = (SharedUserSetting) obj;
4562                return sus.pkgPrivateFlags;
4563            } else if (obj instanceof PackageSetting) {
4564                final PackageSetting ps = (PackageSetting) obj;
4565                return ps.pkgPrivateFlags;
4566            }
4567        }
4568        return 0;
4569    }
4570
4571    @Override
4572    public boolean isUidPrivileged(int uid) {
4573        uid = UserHandle.getAppId(uid);
4574        // reader
4575        synchronized (mPackages) {
4576            Object obj = mSettings.getUserIdLPr(uid);
4577            if (obj instanceof SharedUserSetting) {
4578                final SharedUserSetting sus = (SharedUserSetting) obj;
4579                final Iterator<PackageSetting> it = sus.packages.iterator();
4580                while (it.hasNext()) {
4581                    if (it.next().isPrivileged()) {
4582                        return true;
4583                    }
4584                }
4585            } else if (obj instanceof PackageSetting) {
4586                final PackageSetting ps = (PackageSetting) obj;
4587                return ps.isPrivileged();
4588            }
4589        }
4590        return false;
4591    }
4592
4593    @Override
4594    public String[] getAppOpPermissionPackages(String permissionName) {
4595        synchronized (mPackages) {
4596            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4597            if (pkgs == null) {
4598                return null;
4599            }
4600            return pkgs.toArray(new String[pkgs.size()]);
4601        }
4602    }
4603
4604    @Override
4605    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4606            int flags, int userId) {
4607        if (!sUserManager.exists(userId)) return null;
4608        flags = updateFlagsForResolve(flags, userId, intent);
4609        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4610                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4611        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4612                userId);
4613        final ResolveInfo bestChoice =
4614                chooseBestActivity(intent, resolvedType, flags, query, userId);
4615
4616        if (isEphemeralAllowed(intent, query, userId)) {
4617            final EphemeralResolveInfo ai =
4618                    getEphemeralResolveInfo(intent, resolvedType, userId);
4619            if (ai != null) {
4620                if (DEBUG_EPHEMERAL) {
4621                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4622                }
4623                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4624                bestChoice.ephemeralResolveInfo = ai;
4625            }
4626        }
4627        return bestChoice;
4628    }
4629
4630    @Override
4631    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4632            IntentFilter filter, int match, ComponentName activity) {
4633        final int userId = UserHandle.getCallingUserId();
4634        if (DEBUG_PREFERRED) {
4635            Log.v(TAG, "setLastChosenActivity intent=" + intent
4636                + " resolvedType=" + resolvedType
4637                + " flags=" + flags
4638                + " filter=" + filter
4639                + " match=" + match
4640                + " activity=" + activity);
4641            filter.dump(new PrintStreamPrinter(System.out), "    ");
4642        }
4643        intent.setComponent(null);
4644        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4645                userId);
4646        // Find any earlier preferred or last chosen entries and nuke them
4647        findPreferredActivity(intent, resolvedType,
4648                flags, query, 0, false, true, false, userId);
4649        // Add the new activity as the last chosen for this filter
4650        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4651                "Setting last chosen");
4652    }
4653
4654    @Override
4655    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4656        final int userId = UserHandle.getCallingUserId();
4657        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4658        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4659                userId);
4660        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4661                false, false, false, userId);
4662    }
4663
4664
4665    private boolean isEphemeralAllowed(
4666            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4667        // Short circuit and return early if possible.
4668        if (DISABLE_EPHEMERAL_APPS) {
4669            return false;
4670        }
4671        final int callingUser = UserHandle.getCallingUserId();
4672        if (callingUser != UserHandle.USER_SYSTEM) {
4673            return false;
4674        }
4675        if (mEphemeralResolverConnection == null) {
4676            return false;
4677        }
4678        if (intent.getComponent() != null) {
4679            return false;
4680        }
4681        if (intent.getPackage() != null) {
4682            return false;
4683        }
4684        final boolean isWebUri = hasWebURI(intent);
4685        if (!isWebUri) {
4686            return false;
4687        }
4688        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4689        synchronized (mPackages) {
4690            final int count = resolvedActivites.size();
4691            for (int n = 0; n < count; n++) {
4692                ResolveInfo info = resolvedActivites.get(n);
4693                String packageName = info.activityInfo.packageName;
4694                PackageSetting ps = mSettings.mPackages.get(packageName);
4695                if (ps != null) {
4696                    // Try to get the status from User settings first
4697                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4698                    int status = (int) (packedStatus >> 32);
4699                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4700                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4701                        if (DEBUG_EPHEMERAL) {
4702                            Slog.v(TAG, "DENY ephemeral apps;"
4703                                + " pkg: " + packageName + ", status: " + status);
4704                        }
4705                        return false;
4706                    }
4707                }
4708            }
4709        }
4710        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4711        return true;
4712    }
4713
4714    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4715            int userId) {
4716        MessageDigest digest = null;
4717        try {
4718            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4719        } catch (NoSuchAlgorithmException e) {
4720            // If we can't create a digest, ignore ephemeral apps.
4721            return null;
4722        }
4723
4724        final byte[] hostBytes = intent.getData().getHost().getBytes();
4725        final byte[] digestBytes = digest.digest(hostBytes);
4726        int shaPrefix =
4727                digestBytes[0] << 24
4728                | digestBytes[1] << 16
4729                | digestBytes[2] << 8
4730                | digestBytes[3] << 0;
4731        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4732                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4733        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4734            // No hash prefix match; there are no ephemeral apps for this domain.
4735            return null;
4736        }
4737        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4738            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4739            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4740                continue;
4741            }
4742            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4743            // No filters; this should never happen.
4744            if (filters.isEmpty()) {
4745                continue;
4746            }
4747            // We have a domain match; resolve the filters to see if anything matches.
4748            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4749            for (int j = filters.size() - 1; j >= 0; --j) {
4750                final EphemeralResolveIntentInfo intentInfo =
4751                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4752                ephemeralResolver.addFilter(intentInfo);
4753            }
4754            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4755                    intent, resolvedType, false /*defaultOnly*/, userId);
4756            if (!matchedResolveInfoList.isEmpty()) {
4757                return matchedResolveInfoList.get(0);
4758            }
4759        }
4760        // Hash or filter mis-match; no ephemeral apps for this domain.
4761        return null;
4762    }
4763
4764    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4765            int flags, List<ResolveInfo> query, int userId) {
4766        if (query != null) {
4767            final int N = query.size();
4768            if (N == 1) {
4769                return query.get(0);
4770            } else if (N > 1) {
4771                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4772                // If there is more than one activity with the same priority,
4773                // then let the user decide between them.
4774                ResolveInfo r0 = query.get(0);
4775                ResolveInfo r1 = query.get(1);
4776                if (DEBUG_INTENT_MATCHING || debug) {
4777                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4778                            + r1.activityInfo.name + "=" + r1.priority);
4779                }
4780                // If the first activity has a higher priority, or a different
4781                // default, then it is always desirable to pick it.
4782                if (r0.priority != r1.priority
4783                        || r0.preferredOrder != r1.preferredOrder
4784                        || r0.isDefault != r1.isDefault) {
4785                    return query.get(0);
4786                }
4787                // If we have saved a preference for a preferred activity for
4788                // this Intent, use that.
4789                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4790                        flags, query, r0.priority, true, false, debug, userId);
4791                if (ri != null) {
4792                    return ri;
4793                }
4794                ri = new ResolveInfo(mResolveInfo);
4795                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4796                ri.activityInfo.applicationInfo = new ApplicationInfo(
4797                        ri.activityInfo.applicationInfo);
4798                if (userId != 0) {
4799                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4800                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4801                }
4802                // Make sure that the resolver is displayable in car mode
4803                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4804                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4805                return ri;
4806            }
4807        }
4808        return null;
4809    }
4810
4811    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4812            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4813        final int N = query.size();
4814        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4815                .get(userId);
4816        // Get the list of persistent preferred activities that handle the intent
4817        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4818        List<PersistentPreferredActivity> pprefs = ppir != null
4819                ? ppir.queryIntent(intent, resolvedType,
4820                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4821                : null;
4822        if (pprefs != null && pprefs.size() > 0) {
4823            final int M = pprefs.size();
4824            for (int i=0; i<M; i++) {
4825                final PersistentPreferredActivity ppa = pprefs.get(i);
4826                if (DEBUG_PREFERRED || debug) {
4827                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4828                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4829                            + "\n  component=" + ppa.mComponent);
4830                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4831                }
4832                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4833                        flags | MATCH_DISABLED_COMPONENTS, userId);
4834                if (DEBUG_PREFERRED || debug) {
4835                    Slog.v(TAG, "Found persistent preferred activity:");
4836                    if (ai != null) {
4837                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4838                    } else {
4839                        Slog.v(TAG, "  null");
4840                    }
4841                }
4842                if (ai == null) {
4843                    // This previously registered persistent preferred activity
4844                    // component is no longer known. Ignore it and do NOT remove it.
4845                    continue;
4846                }
4847                for (int j=0; j<N; j++) {
4848                    final ResolveInfo ri = query.get(j);
4849                    if (!ri.activityInfo.applicationInfo.packageName
4850                            .equals(ai.applicationInfo.packageName)) {
4851                        continue;
4852                    }
4853                    if (!ri.activityInfo.name.equals(ai.name)) {
4854                        continue;
4855                    }
4856                    //  Found a persistent preference that can handle the intent.
4857                    if (DEBUG_PREFERRED || debug) {
4858                        Slog.v(TAG, "Returning persistent preferred activity: " +
4859                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4860                    }
4861                    return ri;
4862                }
4863            }
4864        }
4865        return null;
4866    }
4867
4868    // TODO: handle preferred activities missing while user has amnesia
4869    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4870            List<ResolveInfo> query, int priority, boolean always,
4871            boolean removeMatches, boolean debug, int userId) {
4872        if (!sUserManager.exists(userId)) return null;
4873        flags = updateFlagsForResolve(flags, userId, intent);
4874        // writer
4875        synchronized (mPackages) {
4876            if (intent.getSelector() != null) {
4877                intent = intent.getSelector();
4878            }
4879            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4880
4881            // Try to find a matching persistent preferred activity.
4882            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4883                    debug, userId);
4884
4885            // If a persistent preferred activity matched, use it.
4886            if (pri != null) {
4887                return pri;
4888            }
4889
4890            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4891            // Get the list of preferred activities that handle the intent
4892            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4893            List<PreferredActivity> prefs = pir != null
4894                    ? pir.queryIntent(intent, resolvedType,
4895                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4896                    : null;
4897            if (prefs != null && prefs.size() > 0) {
4898                boolean changed = false;
4899                try {
4900                    // First figure out how good the original match set is.
4901                    // We will only allow preferred activities that came
4902                    // from the same match quality.
4903                    int match = 0;
4904
4905                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4906
4907                    final int N = query.size();
4908                    for (int j=0; j<N; j++) {
4909                        final ResolveInfo ri = query.get(j);
4910                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4911                                + ": 0x" + Integer.toHexString(match));
4912                        if (ri.match > match) {
4913                            match = ri.match;
4914                        }
4915                    }
4916
4917                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4918                            + Integer.toHexString(match));
4919
4920                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4921                    final int M = prefs.size();
4922                    for (int i=0; i<M; i++) {
4923                        final PreferredActivity pa = prefs.get(i);
4924                        if (DEBUG_PREFERRED || debug) {
4925                            Slog.v(TAG, "Checking PreferredActivity ds="
4926                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4927                                    + "\n  component=" + pa.mPref.mComponent);
4928                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4929                        }
4930                        if (pa.mPref.mMatch != match) {
4931                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4932                                    + Integer.toHexString(pa.mPref.mMatch));
4933                            continue;
4934                        }
4935                        // If it's not an "always" type preferred activity and that's what we're
4936                        // looking for, skip it.
4937                        if (always && !pa.mPref.mAlways) {
4938                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4939                            continue;
4940                        }
4941                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4942                                flags | MATCH_DISABLED_COMPONENTS, userId);
4943                        if (DEBUG_PREFERRED || debug) {
4944                            Slog.v(TAG, "Found preferred activity:");
4945                            if (ai != null) {
4946                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4947                            } else {
4948                                Slog.v(TAG, "  null");
4949                            }
4950                        }
4951                        if (ai == null) {
4952                            // This previously registered preferred activity
4953                            // component is no longer known.  Most likely an update
4954                            // to the app was installed and in the new version this
4955                            // component no longer exists.  Clean it up by removing
4956                            // it from the preferred activities list, and skip it.
4957                            Slog.w(TAG, "Removing dangling preferred activity: "
4958                                    + pa.mPref.mComponent);
4959                            pir.removeFilter(pa);
4960                            changed = true;
4961                            continue;
4962                        }
4963                        for (int j=0; j<N; j++) {
4964                            final ResolveInfo ri = query.get(j);
4965                            if (!ri.activityInfo.applicationInfo.packageName
4966                                    .equals(ai.applicationInfo.packageName)) {
4967                                continue;
4968                            }
4969                            if (!ri.activityInfo.name.equals(ai.name)) {
4970                                continue;
4971                            }
4972
4973                            if (removeMatches) {
4974                                pir.removeFilter(pa);
4975                                changed = true;
4976                                if (DEBUG_PREFERRED) {
4977                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4978                                }
4979                                break;
4980                            }
4981
4982                            // Okay we found a previously set preferred or last chosen app.
4983                            // If the result set is different from when this
4984                            // was created, we need to clear it and re-ask the
4985                            // user their preference, if we're looking for an "always" type entry.
4986                            if (always && !pa.mPref.sameSet(query)) {
4987                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4988                                        + intent + " type " + resolvedType);
4989                                if (DEBUG_PREFERRED) {
4990                                    Slog.v(TAG, "Removing preferred activity since set changed "
4991                                            + pa.mPref.mComponent);
4992                                }
4993                                pir.removeFilter(pa);
4994                                // Re-add the filter as a "last chosen" entry (!always)
4995                                PreferredActivity lastChosen = new PreferredActivity(
4996                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4997                                pir.addFilter(lastChosen);
4998                                changed = true;
4999                                return null;
5000                            }
5001
5002                            // Yay! Either the set matched or we're looking for the last chosen
5003                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5004                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5005                            return ri;
5006                        }
5007                    }
5008                } finally {
5009                    if (changed) {
5010                        if (DEBUG_PREFERRED) {
5011                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5012                        }
5013                        scheduleWritePackageRestrictionsLocked(userId);
5014                    }
5015                }
5016            }
5017        }
5018        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5019        return null;
5020    }
5021
5022    /*
5023     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5024     */
5025    @Override
5026    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5027            int targetUserId) {
5028        mContext.enforceCallingOrSelfPermission(
5029                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5030        List<CrossProfileIntentFilter> matches =
5031                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5032        if (matches != null) {
5033            int size = matches.size();
5034            for (int i = 0; i < size; i++) {
5035                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5036            }
5037        }
5038        if (hasWebURI(intent)) {
5039            // cross-profile app linking works only towards the parent.
5040            final UserInfo parent = getProfileParent(sourceUserId);
5041            synchronized(mPackages) {
5042                int flags = updateFlagsForResolve(0, parent.id, intent);
5043                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5044                        intent, resolvedType, flags, sourceUserId, parent.id);
5045                return xpDomainInfo != null;
5046            }
5047        }
5048        return false;
5049    }
5050
5051    private UserInfo getProfileParent(int userId) {
5052        final long identity = Binder.clearCallingIdentity();
5053        try {
5054            return sUserManager.getProfileParent(userId);
5055        } finally {
5056            Binder.restoreCallingIdentity(identity);
5057        }
5058    }
5059
5060    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5061            String resolvedType, int userId) {
5062        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5063        if (resolver != null) {
5064            return resolver.queryIntent(intent, resolvedType, false, userId);
5065        }
5066        return null;
5067    }
5068
5069    @Override
5070    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5071            String resolvedType, int flags, int userId) {
5072        return new ParceledListSlice<>(
5073                queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5074    }
5075
5076    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5077            String resolvedType, int flags, int userId) {
5078        if (!sUserManager.exists(userId)) return Collections.emptyList();
5079        flags = updateFlagsForResolve(flags, userId, intent);
5080        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5081                false /* requireFullPermission */, false /* checkShell */,
5082                "query intent activities");
5083        ComponentName comp = intent.getComponent();
5084        if (comp == null) {
5085            if (intent.getSelector() != null) {
5086                intent = intent.getSelector();
5087                comp = intent.getComponent();
5088            }
5089        }
5090
5091        if (comp != null) {
5092            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5093            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5094            if (ai != null) {
5095                final ResolveInfo ri = new ResolveInfo();
5096                ri.activityInfo = ai;
5097                list.add(ri);
5098            }
5099            return list;
5100        }
5101
5102        // reader
5103        synchronized (mPackages) {
5104            final String pkgName = intent.getPackage();
5105            if (pkgName == null) {
5106                List<CrossProfileIntentFilter> matchingFilters =
5107                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5108                // Check for results that need to skip the current profile.
5109                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5110                        resolvedType, flags, userId);
5111                if (xpResolveInfo != null) {
5112                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5113                    result.add(xpResolveInfo);
5114                    return filterIfNotSystemUser(result, userId);
5115                }
5116
5117                // Check for results in the current profile.
5118                List<ResolveInfo> result = mActivities.queryIntent(
5119                        intent, resolvedType, flags, userId);
5120                result = filterIfNotSystemUser(result, userId);
5121
5122                // Check for cross profile results.
5123                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5124                xpResolveInfo = queryCrossProfileIntents(
5125                        matchingFilters, intent, resolvedType, flags, userId,
5126                        hasNonNegativePriorityResult);
5127                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5128                    boolean isVisibleToUser = filterIfNotSystemUser(
5129                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5130                    if (isVisibleToUser) {
5131                        result.add(xpResolveInfo);
5132                        Collections.sort(result, mResolvePrioritySorter);
5133                    }
5134                }
5135                if (hasWebURI(intent)) {
5136                    CrossProfileDomainInfo xpDomainInfo = null;
5137                    final UserInfo parent = getProfileParent(userId);
5138                    if (parent != null) {
5139                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5140                                flags, userId, parent.id);
5141                    }
5142                    if (xpDomainInfo != null) {
5143                        if (xpResolveInfo != null) {
5144                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5145                            // in the result.
5146                            result.remove(xpResolveInfo);
5147                        }
5148                        if (result.size() == 0) {
5149                            result.add(xpDomainInfo.resolveInfo);
5150                            return result;
5151                        }
5152                    } else if (result.size() <= 1) {
5153                        return result;
5154                    }
5155                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5156                            xpDomainInfo, userId);
5157                    Collections.sort(result, mResolvePrioritySorter);
5158                }
5159                return result;
5160            }
5161            final PackageParser.Package pkg = mPackages.get(pkgName);
5162            if (pkg != null) {
5163                return filterIfNotSystemUser(
5164                        mActivities.queryIntentForPackage(
5165                                intent, resolvedType, flags, pkg.activities, userId),
5166                        userId);
5167            }
5168            return new ArrayList<ResolveInfo>();
5169        }
5170    }
5171
5172    private static class CrossProfileDomainInfo {
5173        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5174        ResolveInfo resolveInfo;
5175        /* Best domain verification status of the activities found in the other profile */
5176        int bestDomainVerificationStatus;
5177    }
5178
5179    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5180            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5181        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5182                sourceUserId)) {
5183            return null;
5184        }
5185        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5186                resolvedType, flags, parentUserId);
5187
5188        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5189            return null;
5190        }
5191        CrossProfileDomainInfo result = null;
5192        int size = resultTargetUser.size();
5193        for (int i = 0; i < size; i++) {
5194            ResolveInfo riTargetUser = resultTargetUser.get(i);
5195            // Intent filter verification is only for filters that specify a host. So don't return
5196            // those that handle all web uris.
5197            if (riTargetUser.handleAllWebDataURI) {
5198                continue;
5199            }
5200            String packageName = riTargetUser.activityInfo.packageName;
5201            PackageSetting ps = mSettings.mPackages.get(packageName);
5202            if (ps == null) {
5203                continue;
5204            }
5205            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5206            int status = (int)(verificationState >> 32);
5207            if (result == null) {
5208                result = new CrossProfileDomainInfo();
5209                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5210                        sourceUserId, parentUserId);
5211                result.bestDomainVerificationStatus = status;
5212            } else {
5213                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5214                        result.bestDomainVerificationStatus);
5215            }
5216        }
5217        // Don't consider matches with status NEVER across profiles.
5218        if (result != null && result.bestDomainVerificationStatus
5219                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5220            return null;
5221        }
5222        return result;
5223    }
5224
5225    /**
5226     * Verification statuses are ordered from the worse to the best, except for
5227     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5228     */
5229    private int bestDomainVerificationStatus(int status1, int status2) {
5230        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5231            return status2;
5232        }
5233        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5234            return status1;
5235        }
5236        return (int) MathUtils.max(status1, status2);
5237    }
5238
5239    private boolean isUserEnabled(int userId) {
5240        long callingId = Binder.clearCallingIdentity();
5241        try {
5242            UserInfo userInfo = sUserManager.getUserInfo(userId);
5243            return userInfo != null && userInfo.isEnabled();
5244        } finally {
5245            Binder.restoreCallingIdentity(callingId);
5246        }
5247    }
5248
5249    /**
5250     * Filter out activities with systemUserOnly flag set, when current user is not System.
5251     *
5252     * @return filtered list
5253     */
5254    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5255        if (userId == UserHandle.USER_SYSTEM) {
5256            return resolveInfos;
5257        }
5258        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5259            ResolveInfo info = resolveInfos.get(i);
5260            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5261                resolveInfos.remove(i);
5262            }
5263        }
5264        return resolveInfos;
5265    }
5266
5267    /**
5268     * @param resolveInfos list of resolve infos in descending priority order
5269     * @return if the list contains a resolve info with non-negative priority
5270     */
5271    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5272        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5273    }
5274
5275    private static boolean hasWebURI(Intent intent) {
5276        if (intent.getData() == null) {
5277            return false;
5278        }
5279        final String scheme = intent.getScheme();
5280        if (TextUtils.isEmpty(scheme)) {
5281            return false;
5282        }
5283        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5284    }
5285
5286    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5287            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5288            int userId) {
5289        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5290
5291        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5292            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5293                    candidates.size());
5294        }
5295
5296        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5297        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5298        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5299        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5300        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5301        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5302
5303        synchronized (mPackages) {
5304            final int count = candidates.size();
5305            // First, try to use linked apps. Partition the candidates into four lists:
5306            // one for the final results, one for the "do not use ever", one for "undefined status"
5307            // and finally one for "browser app type".
5308            for (int n=0; n<count; n++) {
5309                ResolveInfo info = candidates.get(n);
5310                String packageName = info.activityInfo.packageName;
5311                PackageSetting ps = mSettings.mPackages.get(packageName);
5312                if (ps != null) {
5313                    // Add to the special match all list (Browser use case)
5314                    if (info.handleAllWebDataURI) {
5315                        matchAllList.add(info);
5316                        continue;
5317                    }
5318                    // Try to get the status from User settings first
5319                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5320                    int status = (int)(packedStatus >> 32);
5321                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5322                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5323                        if (DEBUG_DOMAIN_VERIFICATION) {
5324                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5325                                    + " : linkgen=" + linkGeneration);
5326                        }
5327                        // Use link-enabled generation as preferredOrder, i.e.
5328                        // prefer newly-enabled over earlier-enabled.
5329                        info.preferredOrder = linkGeneration;
5330                        alwaysList.add(info);
5331                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5332                        if (DEBUG_DOMAIN_VERIFICATION) {
5333                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5334                        }
5335                        neverList.add(info);
5336                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5337                        if (DEBUG_DOMAIN_VERIFICATION) {
5338                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5339                        }
5340                        alwaysAskList.add(info);
5341                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5342                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5343                        if (DEBUG_DOMAIN_VERIFICATION) {
5344                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5345                        }
5346                        undefinedList.add(info);
5347                    }
5348                }
5349            }
5350
5351            // We'll want to include browser possibilities in a few cases
5352            boolean includeBrowser = false;
5353
5354            // First try to add the "always" resolution(s) for the current user, if any
5355            if (alwaysList.size() > 0) {
5356                result.addAll(alwaysList);
5357            } else {
5358                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5359                result.addAll(undefinedList);
5360                // Maybe add one for the other profile.
5361                if (xpDomainInfo != null && (
5362                        xpDomainInfo.bestDomainVerificationStatus
5363                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5364                    result.add(xpDomainInfo.resolveInfo);
5365                }
5366                includeBrowser = true;
5367            }
5368
5369            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5370            // If there were 'always' entries their preferred order has been set, so we also
5371            // back that off to make the alternatives equivalent
5372            if (alwaysAskList.size() > 0) {
5373                for (ResolveInfo i : result) {
5374                    i.preferredOrder = 0;
5375                }
5376                result.addAll(alwaysAskList);
5377                includeBrowser = true;
5378            }
5379
5380            if (includeBrowser) {
5381                // Also add browsers (all of them or only the default one)
5382                if (DEBUG_DOMAIN_VERIFICATION) {
5383                    Slog.v(TAG, "   ...including browsers in candidate set");
5384                }
5385                if ((matchFlags & MATCH_ALL) != 0) {
5386                    result.addAll(matchAllList);
5387                } else {
5388                    // Browser/generic handling case.  If there's a default browser, go straight
5389                    // to that (but only if there is no other higher-priority match).
5390                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5391                    int maxMatchPrio = 0;
5392                    ResolveInfo defaultBrowserMatch = null;
5393                    final int numCandidates = matchAllList.size();
5394                    for (int n = 0; n < numCandidates; n++) {
5395                        ResolveInfo info = matchAllList.get(n);
5396                        // track the highest overall match priority...
5397                        if (info.priority > maxMatchPrio) {
5398                            maxMatchPrio = info.priority;
5399                        }
5400                        // ...and the highest-priority default browser match
5401                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5402                            if (defaultBrowserMatch == null
5403                                    || (defaultBrowserMatch.priority < info.priority)) {
5404                                if (debug) {
5405                                    Slog.v(TAG, "Considering default browser match " + info);
5406                                }
5407                                defaultBrowserMatch = info;
5408                            }
5409                        }
5410                    }
5411                    if (defaultBrowserMatch != null
5412                            && defaultBrowserMatch.priority >= maxMatchPrio
5413                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5414                    {
5415                        if (debug) {
5416                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5417                        }
5418                        result.add(defaultBrowserMatch);
5419                    } else {
5420                        result.addAll(matchAllList);
5421                    }
5422                }
5423
5424                // If there is nothing selected, add all candidates and remove the ones that the user
5425                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5426                if (result.size() == 0) {
5427                    result.addAll(candidates);
5428                    result.removeAll(neverList);
5429                }
5430            }
5431        }
5432        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5433            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5434                    result.size());
5435            for (ResolveInfo info : result) {
5436                Slog.v(TAG, "  + " + info.activityInfo);
5437            }
5438        }
5439        return result;
5440    }
5441
5442    // Returns a packed value as a long:
5443    //
5444    // high 'int'-sized word: link status: undefined/ask/never/always.
5445    // low 'int'-sized word: relative priority among 'always' results.
5446    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5447        long result = ps.getDomainVerificationStatusForUser(userId);
5448        // if none available, get the master status
5449        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5450            if (ps.getIntentFilterVerificationInfo() != null) {
5451                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5452            }
5453        }
5454        return result;
5455    }
5456
5457    private ResolveInfo querySkipCurrentProfileIntents(
5458            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5459            int flags, int sourceUserId) {
5460        if (matchingFilters != null) {
5461            int size = matchingFilters.size();
5462            for (int i = 0; i < size; i ++) {
5463                CrossProfileIntentFilter filter = matchingFilters.get(i);
5464                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5465                    // Checking if there are activities in the target user that can handle the
5466                    // intent.
5467                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5468                            resolvedType, flags, sourceUserId);
5469                    if (resolveInfo != null) {
5470                        return resolveInfo;
5471                    }
5472                }
5473            }
5474        }
5475        return null;
5476    }
5477
5478    // Return matching ResolveInfo in target user if any.
5479    private ResolveInfo queryCrossProfileIntents(
5480            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5481            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5482        if (matchingFilters != null) {
5483            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5484            // match the same intent. For performance reasons, it is better not to
5485            // run queryIntent twice for the same userId
5486            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5487            int size = matchingFilters.size();
5488            for (int i = 0; i < size; i++) {
5489                CrossProfileIntentFilter filter = matchingFilters.get(i);
5490                int targetUserId = filter.getTargetUserId();
5491                boolean skipCurrentProfile =
5492                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5493                boolean skipCurrentProfileIfNoMatchFound =
5494                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5495                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5496                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5497                    // Checking if there are activities in the target user that can handle the
5498                    // intent.
5499                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5500                            resolvedType, flags, sourceUserId);
5501                    if (resolveInfo != null) return resolveInfo;
5502                    alreadyTriedUserIds.put(targetUserId, true);
5503                }
5504            }
5505        }
5506        return null;
5507    }
5508
5509    /**
5510     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5511     * will forward the intent to the filter's target user.
5512     * Otherwise, returns null.
5513     */
5514    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5515            String resolvedType, int flags, int sourceUserId) {
5516        int targetUserId = filter.getTargetUserId();
5517        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5518                resolvedType, flags, targetUserId);
5519        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5520            // If all the matches in the target profile are suspended, return null.
5521            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5522                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5523                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5524                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5525                            targetUserId);
5526                }
5527            }
5528        }
5529        return null;
5530    }
5531
5532    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5533            int sourceUserId, int targetUserId) {
5534        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5535        long ident = Binder.clearCallingIdentity();
5536        boolean targetIsProfile;
5537        try {
5538            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5539        } finally {
5540            Binder.restoreCallingIdentity(ident);
5541        }
5542        String className;
5543        if (targetIsProfile) {
5544            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5545        } else {
5546            className = FORWARD_INTENT_TO_PARENT;
5547        }
5548        ComponentName forwardingActivityComponentName = new ComponentName(
5549                mAndroidApplication.packageName, className);
5550        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5551                sourceUserId);
5552        if (!targetIsProfile) {
5553            forwardingActivityInfo.showUserIcon = targetUserId;
5554            forwardingResolveInfo.noResourceId = true;
5555        }
5556        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5557        forwardingResolveInfo.priority = 0;
5558        forwardingResolveInfo.preferredOrder = 0;
5559        forwardingResolveInfo.match = 0;
5560        forwardingResolveInfo.isDefault = true;
5561        forwardingResolveInfo.filter = filter;
5562        forwardingResolveInfo.targetUserId = targetUserId;
5563        return forwardingResolveInfo;
5564    }
5565
5566    @Override
5567    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5568            Intent[] specifics, String[] specificTypes, Intent intent,
5569            String resolvedType, int flags, int userId) {
5570        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5571                specificTypes, intent, resolvedType, flags, userId));
5572    }
5573
5574    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5575            Intent[] specifics, String[] specificTypes, Intent intent,
5576            String resolvedType, int flags, int userId) {
5577        if (!sUserManager.exists(userId)) return Collections.emptyList();
5578        flags = updateFlagsForResolve(flags, userId, intent);
5579        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5580                false /* requireFullPermission */, false /* checkShell */,
5581                "query intent activity options");
5582        final String resultsAction = intent.getAction();
5583
5584        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5585                | PackageManager.GET_RESOLVED_FILTER, userId);
5586
5587        if (DEBUG_INTENT_MATCHING) {
5588            Log.v(TAG, "Query " + intent + ": " + results);
5589        }
5590
5591        int specificsPos = 0;
5592        int N;
5593
5594        // todo: note that the algorithm used here is O(N^2).  This
5595        // isn't a problem in our current environment, but if we start running
5596        // into situations where we have more than 5 or 10 matches then this
5597        // should probably be changed to something smarter...
5598
5599        // First we go through and resolve each of the specific items
5600        // that were supplied, taking care of removing any corresponding
5601        // duplicate items in the generic resolve list.
5602        if (specifics != null) {
5603            for (int i=0; i<specifics.length; i++) {
5604                final Intent sintent = specifics[i];
5605                if (sintent == null) {
5606                    continue;
5607                }
5608
5609                if (DEBUG_INTENT_MATCHING) {
5610                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5611                }
5612
5613                String action = sintent.getAction();
5614                if (resultsAction != null && resultsAction.equals(action)) {
5615                    // If this action was explicitly requested, then don't
5616                    // remove things that have it.
5617                    action = null;
5618                }
5619
5620                ResolveInfo ri = null;
5621                ActivityInfo ai = null;
5622
5623                ComponentName comp = sintent.getComponent();
5624                if (comp == null) {
5625                    ri = resolveIntent(
5626                        sintent,
5627                        specificTypes != null ? specificTypes[i] : null,
5628                            flags, userId);
5629                    if (ri == null) {
5630                        continue;
5631                    }
5632                    if (ri == mResolveInfo) {
5633                        // ACK!  Must do something better with this.
5634                    }
5635                    ai = ri.activityInfo;
5636                    comp = new ComponentName(ai.applicationInfo.packageName,
5637                            ai.name);
5638                } else {
5639                    ai = getActivityInfo(comp, flags, userId);
5640                    if (ai == null) {
5641                        continue;
5642                    }
5643                }
5644
5645                // Look for any generic query activities that are duplicates
5646                // of this specific one, and remove them from the results.
5647                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5648                N = results.size();
5649                int j;
5650                for (j=specificsPos; j<N; j++) {
5651                    ResolveInfo sri = results.get(j);
5652                    if ((sri.activityInfo.name.equals(comp.getClassName())
5653                            && sri.activityInfo.applicationInfo.packageName.equals(
5654                                    comp.getPackageName()))
5655                        || (action != null && sri.filter.matchAction(action))) {
5656                        results.remove(j);
5657                        if (DEBUG_INTENT_MATCHING) Log.v(
5658                            TAG, "Removing duplicate item from " + j
5659                            + " due to specific " + specificsPos);
5660                        if (ri == null) {
5661                            ri = sri;
5662                        }
5663                        j--;
5664                        N--;
5665                    }
5666                }
5667
5668                // Add this specific item to its proper place.
5669                if (ri == null) {
5670                    ri = new ResolveInfo();
5671                    ri.activityInfo = ai;
5672                }
5673                results.add(specificsPos, ri);
5674                ri.specificIndex = i;
5675                specificsPos++;
5676            }
5677        }
5678
5679        // Now we go through the remaining generic results and remove any
5680        // duplicate actions that are found here.
5681        N = results.size();
5682        for (int i=specificsPos; i<N-1; i++) {
5683            final ResolveInfo rii = results.get(i);
5684            if (rii.filter == null) {
5685                continue;
5686            }
5687
5688            // Iterate over all of the actions of this result's intent
5689            // filter...  typically this should be just one.
5690            final Iterator<String> it = rii.filter.actionsIterator();
5691            if (it == null) {
5692                continue;
5693            }
5694            while (it.hasNext()) {
5695                final String action = it.next();
5696                if (resultsAction != null && resultsAction.equals(action)) {
5697                    // If this action was explicitly requested, then don't
5698                    // remove things that have it.
5699                    continue;
5700                }
5701                for (int j=i+1; j<N; j++) {
5702                    final ResolveInfo rij = results.get(j);
5703                    if (rij.filter != null && rij.filter.hasAction(action)) {
5704                        results.remove(j);
5705                        if (DEBUG_INTENT_MATCHING) Log.v(
5706                            TAG, "Removing duplicate item from " + j
5707                            + " due to action " + action + " at " + i);
5708                        j--;
5709                        N--;
5710                    }
5711                }
5712            }
5713
5714            // If the caller didn't request filter information, drop it now
5715            // so we don't have to marshall/unmarshall it.
5716            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5717                rii.filter = null;
5718            }
5719        }
5720
5721        // Filter out the caller activity if so requested.
5722        if (caller != null) {
5723            N = results.size();
5724            for (int i=0; i<N; i++) {
5725                ActivityInfo ainfo = results.get(i).activityInfo;
5726                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5727                        && caller.getClassName().equals(ainfo.name)) {
5728                    results.remove(i);
5729                    break;
5730                }
5731            }
5732        }
5733
5734        // If the caller didn't request filter information,
5735        // drop them now so we don't have to
5736        // marshall/unmarshall it.
5737        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5738            N = results.size();
5739            for (int i=0; i<N; i++) {
5740                results.get(i).filter = null;
5741            }
5742        }
5743
5744        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5745        return results;
5746    }
5747
5748    @Override
5749    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5750            String resolvedType, int flags, int userId) {
5751        return new ParceledListSlice<>(
5752                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5753    }
5754
5755    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5756            String resolvedType, int flags, int userId) {
5757        if (!sUserManager.exists(userId)) return Collections.emptyList();
5758        flags = updateFlagsForResolve(flags, userId, intent);
5759        ComponentName comp = intent.getComponent();
5760        if (comp == null) {
5761            if (intent.getSelector() != null) {
5762                intent = intent.getSelector();
5763                comp = intent.getComponent();
5764            }
5765        }
5766        if (comp != null) {
5767            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5768            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5769            if (ai != null) {
5770                ResolveInfo ri = new ResolveInfo();
5771                ri.activityInfo = ai;
5772                list.add(ri);
5773            }
5774            return list;
5775        }
5776
5777        // reader
5778        synchronized (mPackages) {
5779            String pkgName = intent.getPackage();
5780            if (pkgName == null) {
5781                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5782            }
5783            final PackageParser.Package pkg = mPackages.get(pkgName);
5784            if (pkg != null) {
5785                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5786                        userId);
5787            }
5788            return Collections.emptyList();
5789        }
5790    }
5791
5792    @Override
5793    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5794        if (!sUserManager.exists(userId)) return null;
5795        flags = updateFlagsForResolve(flags, userId, intent);
5796        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5797        if (query != null) {
5798            if (query.size() >= 1) {
5799                // If there is more than one service with the same priority,
5800                // just arbitrarily pick the first one.
5801                return query.get(0);
5802            }
5803        }
5804        return null;
5805    }
5806
5807    @Override
5808    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5809            String resolvedType, int flags, int userId) {
5810        return new ParceledListSlice<>(
5811                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5812    }
5813
5814    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5815            String resolvedType, int flags, int userId) {
5816        if (!sUserManager.exists(userId)) return Collections.emptyList();
5817        flags = updateFlagsForResolve(flags, userId, intent);
5818        ComponentName comp = intent.getComponent();
5819        if (comp == null) {
5820            if (intent.getSelector() != null) {
5821                intent = intent.getSelector();
5822                comp = intent.getComponent();
5823            }
5824        }
5825        if (comp != null) {
5826            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5827            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5828            if (si != null) {
5829                final ResolveInfo ri = new ResolveInfo();
5830                ri.serviceInfo = si;
5831                list.add(ri);
5832            }
5833            return list;
5834        }
5835
5836        // reader
5837        synchronized (mPackages) {
5838            String pkgName = intent.getPackage();
5839            if (pkgName == null) {
5840                return mServices.queryIntent(intent, resolvedType, flags, userId);
5841            }
5842            final PackageParser.Package pkg = mPackages.get(pkgName);
5843            if (pkg != null) {
5844                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5845                        userId);
5846            }
5847            return Collections.emptyList();
5848        }
5849    }
5850
5851    @Override
5852    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5853            String resolvedType, int flags, int userId) {
5854        return new ParceledListSlice<>(
5855                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5856    }
5857
5858    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5859            Intent intent, String resolvedType, int flags, int userId) {
5860        if (!sUserManager.exists(userId)) return Collections.emptyList();
5861        flags = updateFlagsForResolve(flags, userId, intent);
5862        ComponentName comp = intent.getComponent();
5863        if (comp == null) {
5864            if (intent.getSelector() != null) {
5865                intent = intent.getSelector();
5866                comp = intent.getComponent();
5867            }
5868        }
5869        if (comp != null) {
5870            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5871            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5872            if (pi != null) {
5873                final ResolveInfo ri = new ResolveInfo();
5874                ri.providerInfo = pi;
5875                list.add(ri);
5876            }
5877            return list;
5878        }
5879
5880        // reader
5881        synchronized (mPackages) {
5882            String pkgName = intent.getPackage();
5883            if (pkgName == null) {
5884                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5885            }
5886            final PackageParser.Package pkg = mPackages.get(pkgName);
5887            if (pkg != null) {
5888                return mProviders.queryIntentForPackage(
5889                        intent, resolvedType, flags, pkg.providers, userId);
5890            }
5891            return Collections.emptyList();
5892        }
5893    }
5894
5895    @Override
5896    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5897        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5898        flags = updateFlagsForPackage(flags, userId, null);
5899        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5900        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5901                true /* requireFullPermission */, false /* checkShell */,
5902                "get installed packages");
5903
5904        // writer
5905        synchronized (mPackages) {
5906            ArrayList<PackageInfo> list;
5907            if (listUninstalled) {
5908                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5909                for (PackageSetting ps : mSettings.mPackages.values()) {
5910                    PackageInfo pi;
5911                    if (ps.pkg != null) {
5912                        pi = generatePackageInfo(ps.pkg, flags, userId);
5913                    } else {
5914                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5915                    }
5916                    if (pi != null) {
5917                        list.add(pi);
5918                    }
5919                }
5920            } else {
5921                list = new ArrayList<PackageInfo>(mPackages.size());
5922                for (PackageParser.Package p : mPackages.values()) {
5923                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5924                    if (pi != null) {
5925                        list.add(pi);
5926                    }
5927                }
5928            }
5929
5930            return new ParceledListSlice<PackageInfo>(list);
5931        }
5932    }
5933
5934    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5935            String[] permissions, boolean[] tmp, int flags, int userId) {
5936        int numMatch = 0;
5937        final PermissionsState permissionsState = ps.getPermissionsState();
5938        for (int i=0; i<permissions.length; i++) {
5939            final String permission = permissions[i];
5940            if (permissionsState.hasPermission(permission, userId)) {
5941                tmp[i] = true;
5942                numMatch++;
5943            } else {
5944                tmp[i] = false;
5945            }
5946        }
5947        if (numMatch == 0) {
5948            return;
5949        }
5950        PackageInfo pi;
5951        if (ps.pkg != null) {
5952            pi = generatePackageInfo(ps.pkg, flags, userId);
5953        } else {
5954            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5955        }
5956        // The above might return null in cases of uninstalled apps or install-state
5957        // skew across users/profiles.
5958        if (pi != null) {
5959            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5960                if (numMatch == permissions.length) {
5961                    pi.requestedPermissions = permissions;
5962                } else {
5963                    pi.requestedPermissions = new String[numMatch];
5964                    numMatch = 0;
5965                    for (int i=0; i<permissions.length; i++) {
5966                        if (tmp[i]) {
5967                            pi.requestedPermissions[numMatch] = permissions[i];
5968                            numMatch++;
5969                        }
5970                    }
5971                }
5972            }
5973            list.add(pi);
5974        }
5975    }
5976
5977    @Override
5978    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5979            String[] permissions, int flags, int userId) {
5980        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5981        flags = updateFlagsForPackage(flags, userId, permissions);
5982        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5983
5984        // writer
5985        synchronized (mPackages) {
5986            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5987            boolean[] tmpBools = new boolean[permissions.length];
5988            if (listUninstalled) {
5989                for (PackageSetting ps : mSettings.mPackages.values()) {
5990                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5991                }
5992            } else {
5993                for (PackageParser.Package pkg : mPackages.values()) {
5994                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5995                    if (ps != null) {
5996                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5997                                userId);
5998                    }
5999                }
6000            }
6001
6002            return new ParceledListSlice<PackageInfo>(list);
6003        }
6004    }
6005
6006    @Override
6007    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6008        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6009        flags = updateFlagsForApplication(flags, userId, null);
6010        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6011
6012        // writer
6013        synchronized (mPackages) {
6014            ArrayList<ApplicationInfo> list;
6015            if (listUninstalled) {
6016                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6017                for (PackageSetting ps : mSettings.mPackages.values()) {
6018                    ApplicationInfo ai;
6019                    if (ps.pkg != null) {
6020                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6021                                ps.readUserState(userId), userId);
6022                    } else {
6023                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6024                    }
6025                    if (ai != null) {
6026                        list.add(ai);
6027                    }
6028                }
6029            } else {
6030                list = new ArrayList<ApplicationInfo>(mPackages.size());
6031                for (PackageParser.Package p : mPackages.values()) {
6032                    if (p.mExtras != null) {
6033                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6034                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6035                        if (ai != null) {
6036                            list.add(ai);
6037                        }
6038                    }
6039                }
6040            }
6041
6042            return new ParceledListSlice<ApplicationInfo>(list);
6043        }
6044    }
6045
6046    @Override
6047    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6048        if (DISABLE_EPHEMERAL_APPS) {
6049            return null;
6050        }
6051
6052        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6053                "getEphemeralApplications");
6054        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6055                true /* requireFullPermission */, false /* checkShell */,
6056                "getEphemeralApplications");
6057        synchronized (mPackages) {
6058            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6059                    .getEphemeralApplicationsLPw(userId);
6060            if (ephemeralApps != null) {
6061                return new ParceledListSlice<>(ephemeralApps);
6062            }
6063        }
6064        return null;
6065    }
6066
6067    @Override
6068    public boolean isEphemeralApplication(String packageName, int userId) {
6069        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6070                true /* requireFullPermission */, false /* checkShell */,
6071                "isEphemeral");
6072        if (DISABLE_EPHEMERAL_APPS) {
6073            return false;
6074        }
6075
6076        if (!isCallerSameApp(packageName)) {
6077            return false;
6078        }
6079        synchronized (mPackages) {
6080            PackageParser.Package pkg = mPackages.get(packageName);
6081            if (pkg != null) {
6082                return pkg.applicationInfo.isEphemeralApp();
6083            }
6084        }
6085        return false;
6086    }
6087
6088    @Override
6089    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6090        if (DISABLE_EPHEMERAL_APPS) {
6091            return null;
6092        }
6093
6094        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6095                true /* requireFullPermission */, false /* checkShell */,
6096                "getCookie");
6097        if (!isCallerSameApp(packageName)) {
6098            return null;
6099        }
6100        synchronized (mPackages) {
6101            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6102                    packageName, userId);
6103        }
6104    }
6105
6106    @Override
6107    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6108        if (DISABLE_EPHEMERAL_APPS) {
6109            return true;
6110        }
6111
6112        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6113                true /* requireFullPermission */, true /* checkShell */,
6114                "setCookie");
6115        if (!isCallerSameApp(packageName)) {
6116            return false;
6117        }
6118        synchronized (mPackages) {
6119            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6120                    packageName, cookie, userId);
6121        }
6122    }
6123
6124    @Override
6125    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6126        if (DISABLE_EPHEMERAL_APPS) {
6127            return null;
6128        }
6129
6130        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6131                "getEphemeralApplicationIcon");
6132        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6133                true /* requireFullPermission */, false /* checkShell */,
6134                "getEphemeralApplicationIcon");
6135        synchronized (mPackages) {
6136            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6137                    packageName, userId);
6138        }
6139    }
6140
6141    private boolean isCallerSameApp(String packageName) {
6142        PackageParser.Package pkg = mPackages.get(packageName);
6143        return pkg != null
6144                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6145    }
6146
6147    @Override
6148    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6149        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6150    }
6151
6152    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6153        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6154
6155        // reader
6156        synchronized (mPackages) {
6157            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6158            final int userId = UserHandle.getCallingUserId();
6159            while (i.hasNext()) {
6160                final PackageParser.Package p = i.next();
6161                if (p.applicationInfo == null) continue;
6162
6163                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6164                        && !p.applicationInfo.isDirectBootAware();
6165                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6166                        && p.applicationInfo.isDirectBootAware();
6167
6168                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6169                        && (!mSafeMode || isSystemApp(p))
6170                        && (matchesUnaware || matchesAware)) {
6171                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6172                    if (ps != null) {
6173                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6174                                ps.readUserState(userId), userId);
6175                        if (ai != null) {
6176                            finalList.add(ai);
6177                        }
6178                    }
6179                }
6180            }
6181        }
6182
6183        return finalList;
6184    }
6185
6186    @Override
6187    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6188        if (!sUserManager.exists(userId)) return null;
6189        flags = updateFlagsForComponent(flags, userId, name);
6190        // reader
6191        synchronized (mPackages) {
6192            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6193            PackageSetting ps = provider != null
6194                    ? mSettings.mPackages.get(provider.owner.packageName)
6195                    : null;
6196            return ps != null
6197                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6198                    ? PackageParser.generateProviderInfo(provider, flags,
6199                            ps.readUserState(userId), userId)
6200                    : null;
6201        }
6202    }
6203
6204    /**
6205     * @deprecated
6206     */
6207    @Deprecated
6208    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6209        // reader
6210        synchronized (mPackages) {
6211            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6212                    .entrySet().iterator();
6213            final int userId = UserHandle.getCallingUserId();
6214            while (i.hasNext()) {
6215                Map.Entry<String, PackageParser.Provider> entry = i.next();
6216                PackageParser.Provider p = entry.getValue();
6217                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6218
6219                if (ps != null && p.syncable
6220                        && (!mSafeMode || (p.info.applicationInfo.flags
6221                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6222                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6223                            ps.readUserState(userId), userId);
6224                    if (info != null) {
6225                        outNames.add(entry.getKey());
6226                        outInfo.add(info);
6227                    }
6228                }
6229            }
6230        }
6231    }
6232
6233    @Override
6234    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6235            int uid, int flags) {
6236        final int userId = processName != null ? UserHandle.getUserId(uid)
6237                : UserHandle.getCallingUserId();
6238        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6239        flags = updateFlagsForComponent(flags, userId, processName);
6240
6241        ArrayList<ProviderInfo> finalList = null;
6242        // reader
6243        synchronized (mPackages) {
6244            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6245            while (i.hasNext()) {
6246                final PackageParser.Provider p = i.next();
6247                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6248                if (ps != null && p.info.authority != null
6249                        && (processName == null
6250                                || (p.info.processName.equals(processName)
6251                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6252                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6253                    if (finalList == null) {
6254                        finalList = new ArrayList<ProviderInfo>(3);
6255                    }
6256                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6257                            ps.readUserState(userId), userId);
6258                    if (info != null) {
6259                        finalList.add(info);
6260                    }
6261                }
6262            }
6263        }
6264
6265        if (finalList != null) {
6266            Collections.sort(finalList, mProviderInitOrderSorter);
6267            return new ParceledListSlice<ProviderInfo>(finalList);
6268        }
6269
6270        return ParceledListSlice.emptyList();
6271    }
6272
6273    @Override
6274    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6275        // reader
6276        synchronized (mPackages) {
6277            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6278            return PackageParser.generateInstrumentationInfo(i, flags);
6279        }
6280    }
6281
6282    @Override
6283    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6284            String targetPackage, int flags) {
6285        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6286    }
6287
6288    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6289            int flags) {
6290        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6291
6292        // reader
6293        synchronized (mPackages) {
6294            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6295            while (i.hasNext()) {
6296                final PackageParser.Instrumentation p = i.next();
6297                if (targetPackage == null
6298                        || targetPackage.equals(p.info.targetPackage)) {
6299                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6300                            flags);
6301                    if (ii != null) {
6302                        finalList.add(ii);
6303                    }
6304                }
6305            }
6306        }
6307
6308        return finalList;
6309    }
6310
6311    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6312        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6313        if (overlays == null) {
6314            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6315            return;
6316        }
6317        for (PackageParser.Package opkg : overlays.values()) {
6318            // Not much to do if idmap fails: we already logged the error
6319            // and we certainly don't want to abort installation of pkg simply
6320            // because an overlay didn't fit properly. For these reasons,
6321            // ignore the return value of createIdmapForPackagePairLI.
6322            createIdmapForPackagePairLI(pkg, opkg);
6323        }
6324    }
6325
6326    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6327            PackageParser.Package opkg) {
6328        if (!opkg.mTrustedOverlay) {
6329            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6330                    opkg.baseCodePath + ": overlay not trusted");
6331            return false;
6332        }
6333        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6334        if (overlaySet == null) {
6335            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6336                    opkg.baseCodePath + " but target package has no known overlays");
6337            return false;
6338        }
6339        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6340        // TODO: generate idmap for split APKs
6341        try {
6342            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6343        } catch (InstallerException e) {
6344            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6345                    + opkg.baseCodePath);
6346            return false;
6347        }
6348        PackageParser.Package[] overlayArray =
6349            overlaySet.values().toArray(new PackageParser.Package[0]);
6350        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6351            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6352                return p1.mOverlayPriority - p2.mOverlayPriority;
6353            }
6354        };
6355        Arrays.sort(overlayArray, cmp);
6356
6357        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6358        int i = 0;
6359        for (PackageParser.Package p : overlayArray) {
6360            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6361        }
6362        return true;
6363    }
6364
6365    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6366        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6367        try {
6368            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6369        } finally {
6370            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6371        }
6372    }
6373
6374    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6375        final File[] files = dir.listFiles();
6376        if (ArrayUtils.isEmpty(files)) {
6377            Log.d(TAG, "No files in app dir " + dir);
6378            return;
6379        }
6380
6381        if (DEBUG_PACKAGE_SCANNING) {
6382            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6383                    + " flags=0x" + Integer.toHexString(parseFlags));
6384        }
6385
6386        for (File file : files) {
6387            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6388                    && !PackageInstallerService.isStageName(file.getName());
6389            if (!isPackage) {
6390                // Ignore entries which are not packages
6391                continue;
6392            }
6393            try {
6394                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6395                        scanFlags, currentTime, null);
6396            } catch (PackageManagerException e) {
6397                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6398
6399                // Delete invalid userdata apps
6400                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6401                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6402                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6403                    removeCodePathLI(file);
6404                }
6405            }
6406        }
6407    }
6408
6409    private static File getSettingsProblemFile() {
6410        File dataDir = Environment.getDataDirectory();
6411        File systemDir = new File(dataDir, "system");
6412        File fname = new File(systemDir, "uiderrors.txt");
6413        return fname;
6414    }
6415
6416    static void reportSettingsProblem(int priority, String msg) {
6417        logCriticalInfo(priority, msg);
6418    }
6419
6420    static void logCriticalInfo(int priority, String msg) {
6421        Slog.println(priority, TAG, msg);
6422        EventLogTags.writePmCriticalInfo(msg);
6423        try {
6424            File fname = getSettingsProblemFile();
6425            FileOutputStream out = new FileOutputStream(fname, true);
6426            PrintWriter pw = new FastPrintWriter(out);
6427            SimpleDateFormat formatter = new SimpleDateFormat();
6428            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6429            pw.println(dateString + ": " + msg);
6430            pw.close();
6431            FileUtils.setPermissions(
6432                    fname.toString(),
6433                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6434                    -1, -1);
6435        } catch (java.io.IOException e) {
6436        }
6437    }
6438
6439    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6440            int parseFlags) throws PackageManagerException {
6441        if (ps != null
6442                && ps.codePath.equals(srcFile)
6443                && ps.timeStamp == srcFile.lastModified()
6444                && !isCompatSignatureUpdateNeeded(pkg)
6445                && !isRecoverSignatureUpdateNeeded(pkg)) {
6446            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6447            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6448            ArraySet<PublicKey> signingKs;
6449            synchronized (mPackages) {
6450                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6451            }
6452            if (ps.signatures.mSignatures != null
6453                    && ps.signatures.mSignatures.length != 0
6454                    && signingKs != null) {
6455                // Optimization: reuse the existing cached certificates
6456                // if the package appears to be unchanged.
6457                pkg.mSignatures = ps.signatures.mSignatures;
6458                pkg.mSigningKeys = signingKs;
6459                return;
6460            }
6461
6462            Slog.w(TAG, "PackageSetting for " + ps.name
6463                    + " is missing signatures.  Collecting certs again to recover them.");
6464        } else {
6465            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6466        }
6467
6468        try {
6469            PackageParser.collectCertificates(pkg, parseFlags);
6470        } catch (PackageParserException e) {
6471            throw PackageManagerException.from(e);
6472        }
6473    }
6474
6475    /**
6476     *  Traces a package scan.
6477     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6478     */
6479    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6480            long currentTime, UserHandle user) throws PackageManagerException {
6481        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6482        try {
6483            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6484        } finally {
6485            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6486        }
6487    }
6488
6489    /**
6490     *  Scans a package and returns the newly parsed package.
6491     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6492     */
6493    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6494            long currentTime, UserHandle user) throws PackageManagerException {
6495        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6496        parseFlags |= mDefParseFlags;
6497        PackageParser pp = new PackageParser();
6498        pp.setSeparateProcesses(mSeparateProcesses);
6499        pp.setOnlyCoreApps(mOnlyCore);
6500        pp.setDisplayMetrics(mMetrics);
6501
6502        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6503            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6504        }
6505
6506        final PackageParser.Package pkg;
6507        try {
6508            pkg = pp.parsePackage(scanFile, parseFlags);
6509        } catch (PackageParserException e) {
6510            throw PackageManagerException.from(e);
6511        }
6512
6513        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6514    }
6515
6516    /**
6517     *  Scans a package and returns the newly parsed package.
6518     *  @throws PackageManagerException on a parse error.
6519     */
6520    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6521            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6522            throws PackageManagerException {
6523        // If the package has children and this is the first dive in the function
6524        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6525        // packages (parent and children) would be successfully scanned before the
6526        // actual scan since scanning mutates internal state and we want to atomically
6527        // install the package and its children.
6528        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6529            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6530                scanFlags |= SCAN_CHECK_ONLY;
6531            }
6532        } else {
6533            scanFlags &= ~SCAN_CHECK_ONLY;
6534        }
6535
6536        // Scan the parent
6537        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6538                scanFlags, currentTime, user);
6539
6540        // Scan the children
6541        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6542        for (int i = 0; i < childCount; i++) {
6543            PackageParser.Package childPackage = pkg.childPackages.get(i);
6544            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6545                    currentTime, user);
6546        }
6547
6548
6549        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6550            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6551        }
6552
6553        return scannedPkg;
6554    }
6555
6556    /**
6557     *  Scans a package and returns the newly parsed package.
6558     *  @throws PackageManagerException on a parse error.
6559     */
6560    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6561            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6562            throws PackageManagerException {
6563        PackageSetting ps = null;
6564        PackageSetting updatedPkg;
6565        // reader
6566        synchronized (mPackages) {
6567            // Look to see if we already know about this package.
6568            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6569            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6570                // This package has been renamed to its original name.  Let's
6571                // use that.
6572                ps = mSettings.peekPackageLPr(oldName);
6573            }
6574            // If there was no original package, see one for the real package name.
6575            if (ps == null) {
6576                ps = mSettings.peekPackageLPr(pkg.packageName);
6577            }
6578            // Check to see if this package could be hiding/updating a system
6579            // package.  Must look for it either under the original or real
6580            // package name depending on our state.
6581            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6582            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6583
6584            // If this is a package we don't know about on the system partition, we
6585            // may need to remove disabled child packages on the system partition
6586            // or may need to not add child packages if the parent apk is updated
6587            // on the data partition and no longer defines this child package.
6588            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6589                // If this is a parent package for an updated system app and this system
6590                // app got an OTA update which no longer defines some of the child packages
6591                // we have to prune them from the disabled system packages.
6592                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6593                if (disabledPs != null) {
6594                    final int scannedChildCount = (pkg.childPackages != null)
6595                            ? pkg.childPackages.size() : 0;
6596                    final int disabledChildCount = disabledPs.childPackageNames != null
6597                            ? disabledPs.childPackageNames.size() : 0;
6598                    for (int i = 0; i < disabledChildCount; i++) {
6599                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6600                        boolean disabledPackageAvailable = false;
6601                        for (int j = 0; j < scannedChildCount; j++) {
6602                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6603                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6604                                disabledPackageAvailable = true;
6605                                break;
6606                            }
6607                         }
6608                         if (!disabledPackageAvailable) {
6609                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6610                         }
6611                    }
6612                }
6613            }
6614        }
6615
6616        boolean updatedPkgBetter = false;
6617        // First check if this is a system package that may involve an update
6618        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6619            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6620            // it needs to drop FLAG_PRIVILEGED.
6621            if (locationIsPrivileged(scanFile)) {
6622                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6623            } else {
6624                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6625            }
6626
6627            if (ps != null && !ps.codePath.equals(scanFile)) {
6628                // The path has changed from what was last scanned...  check the
6629                // version of the new path against what we have stored to determine
6630                // what to do.
6631                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6632                if (pkg.mVersionCode <= ps.versionCode) {
6633                    // The system package has been updated and the code path does not match
6634                    // Ignore entry. Skip it.
6635                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6636                            + " ignored: updated version " + ps.versionCode
6637                            + " better than this " + pkg.mVersionCode);
6638                    if (!updatedPkg.codePath.equals(scanFile)) {
6639                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6640                                + ps.name + " changing from " + updatedPkg.codePathString
6641                                + " to " + scanFile);
6642                        updatedPkg.codePath = scanFile;
6643                        updatedPkg.codePathString = scanFile.toString();
6644                        updatedPkg.resourcePath = scanFile;
6645                        updatedPkg.resourcePathString = scanFile.toString();
6646                    }
6647                    updatedPkg.pkg = pkg;
6648                    updatedPkg.versionCode = pkg.mVersionCode;
6649
6650                    // Update the disabled system child packages to point to the package too.
6651                    final int childCount = updatedPkg.childPackageNames != null
6652                            ? updatedPkg.childPackageNames.size() : 0;
6653                    for (int i = 0; i < childCount; i++) {
6654                        String childPackageName = updatedPkg.childPackageNames.get(i);
6655                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6656                                childPackageName);
6657                        if (updatedChildPkg != null) {
6658                            updatedChildPkg.pkg = pkg;
6659                            updatedChildPkg.versionCode = pkg.mVersionCode;
6660                        }
6661                    }
6662
6663                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6664                            + scanFile + " ignored: updated version " + ps.versionCode
6665                            + " better than this " + pkg.mVersionCode);
6666                } else {
6667                    // The current app on the system partition is better than
6668                    // what we have updated to on the data partition; switch
6669                    // back to the system partition version.
6670                    // At this point, its safely assumed that package installation for
6671                    // apps in system partition will go through. If not there won't be a working
6672                    // version of the app
6673                    // writer
6674                    synchronized (mPackages) {
6675                        // Just remove the loaded entries from package lists.
6676                        mPackages.remove(ps.name);
6677                    }
6678
6679                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6680                            + " reverting from " + ps.codePathString
6681                            + ": new version " + pkg.mVersionCode
6682                            + " better than installed " + ps.versionCode);
6683
6684                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6685                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6686                    synchronized (mInstallLock) {
6687                        args.cleanUpResourcesLI();
6688                    }
6689                    synchronized (mPackages) {
6690                        mSettings.enableSystemPackageLPw(ps.name);
6691                    }
6692                    updatedPkgBetter = true;
6693                }
6694            }
6695        }
6696
6697        if (updatedPkg != null) {
6698            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6699            // initially
6700            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6701
6702            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6703            // flag set initially
6704            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6705                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6706            }
6707        }
6708
6709        // Verify certificates against what was last scanned
6710        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6711
6712        /*
6713         * A new system app appeared, but we already had a non-system one of the
6714         * same name installed earlier.
6715         */
6716        boolean shouldHideSystemApp = false;
6717        if (updatedPkg == null && ps != null
6718                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6719            /*
6720             * Check to make sure the signatures match first. If they don't,
6721             * wipe the installed application and its data.
6722             */
6723            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6724                    != PackageManager.SIGNATURE_MATCH) {
6725                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6726                        + " signatures don't match existing userdata copy; removing");
6727                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6728                ps = null;
6729            } else {
6730                /*
6731                 * If the newly-added system app is an older version than the
6732                 * already installed version, hide it. It will be scanned later
6733                 * and re-added like an update.
6734                 */
6735                if (pkg.mVersionCode <= ps.versionCode) {
6736                    shouldHideSystemApp = true;
6737                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6738                            + " but new version " + pkg.mVersionCode + " better than installed "
6739                            + ps.versionCode + "; hiding system");
6740                } else {
6741                    /*
6742                     * The newly found system app is a newer version that the
6743                     * one previously installed. Simply remove the
6744                     * already-installed application and replace it with our own
6745                     * while keeping the application data.
6746                     */
6747                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6748                            + " reverting from " + ps.codePathString + ": new version "
6749                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6750                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6751                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6752                    synchronized (mInstallLock) {
6753                        args.cleanUpResourcesLI();
6754                    }
6755                }
6756            }
6757        }
6758
6759        // The apk is forward locked (not public) if its code and resources
6760        // are kept in different files. (except for app in either system or
6761        // vendor path).
6762        // TODO grab this value from PackageSettings
6763        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6764            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6765                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6766            }
6767        }
6768
6769        // TODO: extend to support forward-locked splits
6770        String resourcePath = null;
6771        String baseResourcePath = null;
6772        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6773            if (ps != null && ps.resourcePathString != null) {
6774                resourcePath = ps.resourcePathString;
6775                baseResourcePath = ps.resourcePathString;
6776            } else {
6777                // Should not happen at all. Just log an error.
6778                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6779            }
6780        } else {
6781            resourcePath = pkg.codePath;
6782            baseResourcePath = pkg.baseCodePath;
6783        }
6784
6785        // Set application objects path explicitly.
6786        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6787        pkg.setApplicationInfoCodePath(pkg.codePath);
6788        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6789        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6790        pkg.setApplicationInfoResourcePath(resourcePath);
6791        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6792        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6793
6794        // Note that we invoke the following method only if we are about to unpack an application
6795        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6796                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6797
6798        /*
6799         * If the system app should be overridden by a previously installed
6800         * data, hide the system app now and let the /data/app scan pick it up
6801         * again.
6802         */
6803        if (shouldHideSystemApp) {
6804            synchronized (mPackages) {
6805                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6806            }
6807        }
6808
6809        return scannedPkg;
6810    }
6811
6812    private static String fixProcessName(String defProcessName,
6813            String processName, int uid) {
6814        if (processName == null) {
6815            return defProcessName;
6816        }
6817        return processName;
6818    }
6819
6820    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6821            throws PackageManagerException {
6822        if (pkgSetting.signatures.mSignatures != null) {
6823            // Already existing package. Make sure signatures match
6824            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6825                    == PackageManager.SIGNATURE_MATCH;
6826            if (!match) {
6827                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6828                        == PackageManager.SIGNATURE_MATCH;
6829            }
6830            if (!match) {
6831                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6832                        == PackageManager.SIGNATURE_MATCH;
6833            }
6834            if (!match) {
6835                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6836                        + pkg.packageName + " signatures do not match the "
6837                        + "previously installed version; ignoring!");
6838            }
6839        }
6840
6841        // Check for shared user signatures
6842        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6843            // Already existing package. Make sure signatures match
6844            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6845                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6846            if (!match) {
6847                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6848                        == PackageManager.SIGNATURE_MATCH;
6849            }
6850            if (!match) {
6851                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6852                        == PackageManager.SIGNATURE_MATCH;
6853            }
6854            if (!match) {
6855                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6856                        "Package " + pkg.packageName
6857                        + " has no signatures that match those in shared user "
6858                        + pkgSetting.sharedUser.name + "; ignoring!");
6859            }
6860        }
6861    }
6862
6863    /**
6864     * Enforces that only the system UID or root's UID can call a method exposed
6865     * via Binder.
6866     *
6867     * @param message used as message if SecurityException is thrown
6868     * @throws SecurityException if the caller is not system or root
6869     */
6870    private static final void enforceSystemOrRoot(String message) {
6871        final int uid = Binder.getCallingUid();
6872        if (uid != Process.SYSTEM_UID && uid != 0) {
6873            throw new SecurityException(message);
6874        }
6875    }
6876
6877    @Override
6878    public void performFstrimIfNeeded() {
6879        enforceSystemOrRoot("Only the system can request fstrim");
6880
6881        // Before everything else, see whether we need to fstrim.
6882        try {
6883            IMountService ms = PackageHelper.getMountService();
6884            if (ms != null) {
6885                final boolean isUpgrade = isUpgrade();
6886                boolean doTrim = isUpgrade;
6887                if (doTrim) {
6888                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6889                } else {
6890                    final long interval = android.provider.Settings.Global.getLong(
6891                            mContext.getContentResolver(),
6892                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6893                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6894                    if (interval > 0) {
6895                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6896                        if (timeSinceLast > interval) {
6897                            doTrim = true;
6898                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6899                                    + "; running immediately");
6900                        }
6901                    }
6902                }
6903                if (doTrim) {
6904                    if (!isFirstBoot()) {
6905                        try {
6906                            ActivityManagerNative.getDefault().showBootMessage(
6907                                    mContext.getResources().getString(
6908                                            R.string.android_upgrading_fstrim), true);
6909                        } catch (RemoteException e) {
6910                        }
6911                    }
6912                    ms.runMaintenance();
6913                }
6914            } else {
6915                Slog.e(TAG, "Mount service unavailable!");
6916            }
6917        } catch (RemoteException e) {
6918            // Can't happen; MountService is local
6919        }
6920    }
6921
6922    @Override
6923    public void extractPackagesIfNeeded() {
6924        enforceSystemOrRoot("Only the system can request package extraction");
6925
6926        // We need to re-extract after an OTA.
6927        boolean causeUpgrade = isUpgrade();
6928
6929        // First boot or factory reset.
6930        // Note: we also handle devices that are upgrading to N right now as if it is their
6931        //       first boot, as they do not have profile data.
6932        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
6933
6934        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
6935        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
6936
6937        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
6938            return;
6939        }
6940
6941        List<PackageParser.Package> pkgs;
6942        synchronized (mPackages) {
6943            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6944        }
6945
6946        int curr = 0;
6947        int total = pkgs.size();
6948        for (PackageParser.Package pkg : pkgs) {
6949            curr++;
6950
6951            if (DEBUG_DEXOPT) {
6952                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6953            }
6954
6955            if (!isFirstBoot()) {
6956                try {
6957                    ActivityManagerNative.getDefault().showBootMessage(
6958                            mContext.getResources().getString(R.string.android_upgrading_apk,
6959                                    curr, total), true);
6960                } catch (RemoteException e) {
6961                }
6962            }
6963
6964            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6965                // If the cache was pruned, any compiled odex files will likely be out of date
6966                // and would have to be patched (would be SELF_PATCHOAT, which is deprecated).
6967                // Instead, force the extraction in this case.
6968                performDexOpt(pkg.packageName, null /* instructionSet */,
6969                         false /* checkProfiles */,
6970                         causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
6971                         causePrunedCache);
6972            }
6973        }
6974    }
6975
6976    @Override
6977    public void notifyPackageUse(String packageName) {
6978        synchronized (mPackages) {
6979            PackageParser.Package p = mPackages.get(packageName);
6980            if (p == null) {
6981                return;
6982            }
6983            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6984        }
6985    }
6986
6987    // TODO: this is not used nor needed. Delete it.
6988    @Override
6989    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6990        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
6991                getFullCompilerFilter(), false /* force */);
6992    }
6993
6994    @Override
6995    public boolean performDexOpt(String packageName, String instructionSet,
6996            boolean checkProfiles, int compileReason, boolean force) {
6997        return performDexOptTraced(packageName, instructionSet, checkProfiles,
6998                getCompilerFilterForReason(compileReason), force);
6999    }
7000
7001    @Override
7002    public boolean performDexOptMode(String packageName, String instructionSet,
7003            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7004        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7005                targetCompilerFilter, force);
7006    }
7007
7008    private boolean performDexOptTraced(String packageName, String instructionSet,
7009                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7010        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7011        try {
7012            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7013                    targetCompilerFilter, force);
7014        } finally {
7015            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7016        }
7017    }
7018
7019    private boolean performDexOptInternal(String packageName, String instructionSet,
7020                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7021        PackageParser.Package p;
7022        final String targetInstructionSet;
7023        synchronized (mPackages) {
7024            p = mPackages.get(packageName);
7025            if (p == null) {
7026                return false;
7027            }
7028            mPackageUsage.write(false);
7029
7030            targetInstructionSet = instructionSet != null ? instructionSet :
7031                    getPrimaryInstructionSet(p.applicationInfo);
7032        }
7033        long callingId = Binder.clearCallingIdentity();
7034        try {
7035            synchronized (mInstallLock) {
7036                final String[] instructionSets = new String[] { targetInstructionSet };
7037                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7038                        checkProfiles, targetCompilerFilter, force);
7039                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
7040            }
7041        } finally {
7042            Binder.restoreCallingIdentity(callingId);
7043        }
7044    }
7045
7046    public ArraySet<String> getOptimizablePackages() {
7047        ArraySet<String> pkgs = new ArraySet<String>();
7048        synchronized (mPackages) {
7049            for (PackageParser.Package p : mPackages.values()) {
7050                if (PackageDexOptimizer.canOptimizePackage(p)) {
7051                    pkgs.add(p.packageName);
7052                }
7053            }
7054        }
7055        return pkgs;
7056    }
7057
7058    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7059            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7060            boolean force) {
7061        // Select the dex optimizer based on the force parameter.
7062        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7063        //       allocate an object here.
7064        PackageDexOptimizer pdo = force
7065                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7066                : mPackageDexOptimizer;
7067
7068        // Optimize all dependencies first. Note: we ignore the return value and march on
7069        // on errors.
7070        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7071        if (!deps.isEmpty()) {
7072            for (PackageParser.Package depPackage : deps) {
7073                // TODO: Analyze and investigate if we (should) profile libraries.
7074                // Currently this will do a full compilation of the library by default.
7075                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7076                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7077            }
7078        }
7079
7080        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7081    }
7082
7083    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7084        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7085            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7086            Set<String> collectedNames = new HashSet<>();
7087            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7088
7089            retValue.remove(p);
7090
7091            return retValue;
7092        } else {
7093            return Collections.emptyList();
7094        }
7095    }
7096
7097    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7098            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7099        if (!collectedNames.contains(p.packageName)) {
7100            collectedNames.add(p.packageName);
7101            collected.add(p);
7102
7103            if (p.usesLibraries != null) {
7104                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7105            }
7106            if (p.usesOptionalLibraries != null) {
7107                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7108                        collectedNames);
7109            }
7110        }
7111    }
7112
7113    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7114            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7115        for (String libName : libs) {
7116            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7117            if (libPkg != null) {
7118                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7119            }
7120        }
7121    }
7122
7123    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7124        synchronized (mPackages) {
7125            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7126            if (lib != null && lib.apk != null) {
7127                return mPackages.get(lib.apk);
7128            }
7129        }
7130        return null;
7131    }
7132
7133    public void shutdown() {
7134        mPackageUsage.write(true);
7135    }
7136
7137    @Override
7138    public void forceDexOpt(String packageName) {
7139        enforceSystemOrRoot("forceDexOpt");
7140
7141        PackageParser.Package pkg;
7142        synchronized (mPackages) {
7143            pkg = mPackages.get(packageName);
7144            if (pkg == null) {
7145                throw new IllegalArgumentException("Unknown package: " + packageName);
7146            }
7147        }
7148
7149        synchronized (mInstallLock) {
7150            final String[] instructionSets = new String[] {
7151                    getPrimaryInstructionSet(pkg.applicationInfo) };
7152
7153            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7154
7155            // Whoever is calling forceDexOpt wants a fully compiled package.
7156            // Don't use profiles since that may cause compilation to be skipped.
7157            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7158                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7159                    true /* force */);
7160
7161            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7162            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7163                throw new IllegalStateException("Failed to dexopt: " + res);
7164            }
7165        }
7166    }
7167
7168    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7169        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7170            Slog.w(TAG, "Unable to update from " + oldPkg.name
7171                    + " to " + newPkg.packageName
7172                    + ": old package not in system partition");
7173            return false;
7174        } else if (mPackages.get(oldPkg.name) != null) {
7175            Slog.w(TAG, "Unable to update from " + oldPkg.name
7176                    + " to " + newPkg.packageName
7177                    + ": old package still exists");
7178            return false;
7179        }
7180        return true;
7181    }
7182
7183    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7184        // TODO: triage flags as part of 26466827
7185        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7186
7187        boolean res = true;
7188        final int[] users = sUserManager.getUserIds();
7189        for (int user : users) {
7190            try {
7191                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7192            } catch (InstallerException e) {
7193                Slog.w(TAG, "Failed to delete data directory", e);
7194                res = false;
7195            }
7196        }
7197        return res;
7198    }
7199
7200    void removeCodePathLI(File codePath) {
7201        if (codePath.isDirectory()) {
7202            try {
7203                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7204            } catch (InstallerException e) {
7205                Slog.w(TAG, "Failed to remove code path", e);
7206            }
7207        } else {
7208            codePath.delete();
7209        }
7210    }
7211
7212    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7213        try {
7214            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7215        } catch (InstallerException e) {
7216            Slog.w(TAG, "Failed to destroy app data", e);
7217        }
7218    }
7219
7220    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7221            int appId, String seinfo) {
7222        try {
7223            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7224        } catch (InstallerException e) {
7225            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7226        }
7227    }
7228
7229    private void deleteProfilesLI(String packageName, boolean destroy) {
7230        final PackageParser.Package pkg;
7231        synchronized (mPackages) {
7232            pkg = mPackages.get(packageName);
7233        }
7234        if (pkg == null) {
7235            Slog.w(TAG, "Failed to delete profiles. No package: " + packageName);
7236            return;
7237        }
7238        deleteProfilesLI(pkg, destroy);
7239    }
7240
7241    private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) {
7242        try {
7243            if (destroy) {
7244                mInstaller.clearAppProfiles(pkg.packageName);
7245            } else {
7246                mInstaller.destroyAppProfiles(pkg.packageName);
7247            }
7248        } catch (InstallerException ex) {
7249            Log.e(TAG, "Could not delete profiles for package " + pkg.packageName);
7250        }
7251    }
7252
7253    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7254        final PackageParser.Package pkg;
7255        synchronized (mPackages) {
7256            pkg = mPackages.get(packageName);
7257        }
7258        if (pkg == null) {
7259            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7260            return;
7261        }
7262        deleteCodeCacheDirsLI(pkg);
7263    }
7264
7265    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7266        // TODO: triage flags as part of 26466827
7267        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7268
7269        int[] users = sUserManager.getUserIds();
7270        int res = 0;
7271        for (int user : users) {
7272            // Remove the parent code cache
7273            try {
7274                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7275                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7276            } catch (InstallerException e) {
7277                Slog.w(TAG, "Failed to delete code cache directory", e);
7278            }
7279            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7280            for (int i = 0; i < childCount; i++) {
7281                PackageParser.Package childPkg = pkg.childPackages.get(i);
7282                // Remove the child code cache
7283                try {
7284                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7285                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7286                } catch (InstallerException e) {
7287                    Slog.w(TAG, "Failed to delete code cache directory", e);
7288                }
7289            }
7290        }
7291    }
7292
7293    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7294            long lastUpdateTime) {
7295        // Set parent install/update time
7296        PackageSetting ps = (PackageSetting) pkg.mExtras;
7297        if (ps != null) {
7298            ps.firstInstallTime = firstInstallTime;
7299            ps.lastUpdateTime = lastUpdateTime;
7300        }
7301        // Set children install/update time
7302        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7303        for (int i = 0; i < childCount; i++) {
7304            PackageParser.Package childPkg = pkg.childPackages.get(i);
7305            ps = (PackageSetting) childPkg.mExtras;
7306            if (ps != null) {
7307                ps.firstInstallTime = firstInstallTime;
7308                ps.lastUpdateTime = lastUpdateTime;
7309            }
7310        }
7311    }
7312
7313    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7314            PackageParser.Package changingLib) {
7315        if (file.path != null) {
7316            usesLibraryFiles.add(file.path);
7317            return;
7318        }
7319        PackageParser.Package p = mPackages.get(file.apk);
7320        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7321            // If we are doing this while in the middle of updating a library apk,
7322            // then we need to make sure to use that new apk for determining the
7323            // dependencies here.  (We haven't yet finished committing the new apk
7324            // to the package manager state.)
7325            if (p == null || p.packageName.equals(changingLib.packageName)) {
7326                p = changingLib;
7327            }
7328        }
7329        if (p != null) {
7330            usesLibraryFiles.addAll(p.getAllCodePaths());
7331        }
7332    }
7333
7334    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7335            PackageParser.Package changingLib) throws PackageManagerException {
7336        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7337            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7338            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7339            for (int i=0; i<N; i++) {
7340                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7341                if (file == null) {
7342                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7343                            "Package " + pkg.packageName + " requires unavailable shared library "
7344                            + pkg.usesLibraries.get(i) + "; failing!");
7345                }
7346                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7347            }
7348            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7349            for (int i=0; i<N; i++) {
7350                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7351                if (file == null) {
7352                    Slog.w(TAG, "Package " + pkg.packageName
7353                            + " desires unavailable shared library "
7354                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7355                } else {
7356                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7357                }
7358            }
7359            N = usesLibraryFiles.size();
7360            if (N > 0) {
7361                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7362            } else {
7363                pkg.usesLibraryFiles = null;
7364            }
7365        }
7366    }
7367
7368    private static boolean hasString(List<String> list, List<String> which) {
7369        if (list == null) {
7370            return false;
7371        }
7372        for (int i=list.size()-1; i>=0; i--) {
7373            for (int j=which.size()-1; j>=0; j--) {
7374                if (which.get(j).equals(list.get(i))) {
7375                    return true;
7376                }
7377            }
7378        }
7379        return false;
7380    }
7381
7382    private void updateAllSharedLibrariesLPw() {
7383        for (PackageParser.Package pkg : mPackages.values()) {
7384            try {
7385                updateSharedLibrariesLPw(pkg, null);
7386            } catch (PackageManagerException e) {
7387                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7388            }
7389        }
7390    }
7391
7392    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7393            PackageParser.Package changingPkg) {
7394        ArrayList<PackageParser.Package> res = null;
7395        for (PackageParser.Package pkg : mPackages.values()) {
7396            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7397                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7398                if (res == null) {
7399                    res = new ArrayList<PackageParser.Package>();
7400                }
7401                res.add(pkg);
7402                try {
7403                    updateSharedLibrariesLPw(pkg, changingPkg);
7404                } catch (PackageManagerException e) {
7405                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7406                }
7407            }
7408        }
7409        return res;
7410    }
7411
7412    /**
7413     * Derive the value of the {@code cpuAbiOverride} based on the provided
7414     * value and an optional stored value from the package settings.
7415     */
7416    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7417        String cpuAbiOverride = null;
7418
7419        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7420            cpuAbiOverride = null;
7421        } else if (abiOverride != null) {
7422            cpuAbiOverride = abiOverride;
7423        } else if (settings != null) {
7424            cpuAbiOverride = settings.cpuAbiOverrideString;
7425        }
7426
7427        return cpuAbiOverride;
7428    }
7429
7430    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7431            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7432        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7433        // If the package has children and this is the first dive in the function
7434        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7435        // whether all packages (parent and children) would be successfully scanned
7436        // before the actual scan since scanning mutates internal state and we want
7437        // to atomically install the package and its children.
7438        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7439            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7440                scanFlags |= SCAN_CHECK_ONLY;
7441            }
7442        } else {
7443            scanFlags &= ~SCAN_CHECK_ONLY;
7444        }
7445
7446        final PackageParser.Package scannedPkg;
7447        try {
7448            // Scan the parent
7449            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7450            // Scan the children
7451            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7452            for (int i = 0; i < childCount; i++) {
7453                PackageParser.Package childPkg = pkg.childPackages.get(i);
7454                scanPackageLI(childPkg, parseFlags,
7455                        scanFlags, currentTime, user);
7456            }
7457        } finally {
7458            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7459        }
7460
7461        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7462            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7463        }
7464
7465        return scannedPkg;
7466    }
7467
7468    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7469            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7470        boolean success = false;
7471        try {
7472            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7473                    currentTime, user);
7474            success = true;
7475            return res;
7476        } finally {
7477            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7478                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7479            }
7480        }
7481    }
7482
7483    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7484            int scanFlags, long currentTime, UserHandle user)
7485            throws PackageManagerException {
7486        final File scanFile = new File(pkg.codePath);
7487        if (pkg.applicationInfo.getCodePath() == null ||
7488                pkg.applicationInfo.getResourcePath() == null) {
7489            // Bail out. The resource and code paths haven't been set.
7490            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7491                    "Code and resource paths haven't been set correctly");
7492        }
7493
7494        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7495            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7496        } else {
7497            // Only allow system apps to be flagged as core apps.
7498            pkg.coreApp = false;
7499        }
7500
7501        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7502            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7503        }
7504
7505        if (mCustomResolverComponentName != null &&
7506                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7507            setUpCustomResolverActivity(pkg);
7508        }
7509
7510        if (pkg.packageName.equals("android")) {
7511            synchronized (mPackages) {
7512                if (mAndroidApplication != null) {
7513                    Slog.w(TAG, "*************************************************");
7514                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7515                    Slog.w(TAG, " file=" + scanFile);
7516                    Slog.w(TAG, "*************************************************");
7517                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7518                            "Core android package being redefined.  Skipping.");
7519                }
7520
7521                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7522                    // Set up information for our fall-back user intent resolution activity.
7523                    mPlatformPackage = pkg;
7524                    pkg.mVersionCode = mSdkVersion;
7525                    mAndroidApplication = pkg.applicationInfo;
7526
7527                    if (!mResolverReplaced) {
7528                        mResolveActivity.applicationInfo = mAndroidApplication;
7529                        mResolveActivity.name = ResolverActivity.class.getName();
7530                        mResolveActivity.packageName = mAndroidApplication.packageName;
7531                        mResolveActivity.processName = "system:ui";
7532                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7533                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7534                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7535                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7536                        mResolveActivity.exported = true;
7537                        mResolveActivity.enabled = true;
7538                        mResolveInfo.activityInfo = mResolveActivity;
7539                        mResolveInfo.priority = 0;
7540                        mResolveInfo.preferredOrder = 0;
7541                        mResolveInfo.match = 0;
7542                        mResolveComponentName = new ComponentName(
7543                                mAndroidApplication.packageName, mResolveActivity.name);
7544                    }
7545                }
7546            }
7547        }
7548
7549        if (DEBUG_PACKAGE_SCANNING) {
7550            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7551                Log.d(TAG, "Scanning package " + pkg.packageName);
7552        }
7553
7554        synchronized (mPackages) {
7555            if (mPackages.containsKey(pkg.packageName)
7556                    || mSharedLibraries.containsKey(pkg.packageName)) {
7557                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7558                        "Application package " + pkg.packageName
7559                                + " already installed.  Skipping duplicate.");
7560            }
7561
7562            // If we're only installing presumed-existing packages, require that the
7563            // scanned APK is both already known and at the path previously established
7564            // for it.  Previously unknown packages we pick up normally, but if we have an
7565            // a priori expectation about this package's install presence, enforce it.
7566            // With a singular exception for new system packages. When an OTA contains
7567            // a new system package, we allow the codepath to change from a system location
7568            // to the user-installed location. If we don't allow this change, any newer,
7569            // user-installed version of the application will be ignored.
7570            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7571                if (mExpectingBetter.containsKey(pkg.packageName)) {
7572                    logCriticalInfo(Log.WARN,
7573                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7574                } else {
7575                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7576                    if (known != null) {
7577                        if (DEBUG_PACKAGE_SCANNING) {
7578                            Log.d(TAG, "Examining " + pkg.codePath
7579                                    + " and requiring known paths " + known.codePathString
7580                                    + " & " + known.resourcePathString);
7581                        }
7582                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7583                                || !pkg.applicationInfo.getResourcePath().equals(
7584                                known.resourcePathString)) {
7585                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7586                                    "Application package " + pkg.packageName
7587                                            + " found at " + pkg.applicationInfo.getCodePath()
7588                                            + " but expected at " + known.codePathString
7589                                            + "; ignoring.");
7590                        }
7591                    }
7592                }
7593            }
7594        }
7595
7596        // Initialize package source and resource directories
7597        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7598        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7599
7600        SharedUserSetting suid = null;
7601        PackageSetting pkgSetting = null;
7602
7603        if (!isSystemApp(pkg)) {
7604            // Only system apps can use these features.
7605            pkg.mOriginalPackages = null;
7606            pkg.mRealPackage = null;
7607            pkg.mAdoptPermissions = null;
7608        }
7609
7610        // Getting the package setting may have a side-effect, so if we
7611        // are only checking if scan would succeed, stash a copy of the
7612        // old setting to restore at the end.
7613        PackageSetting nonMutatedPs = null;
7614
7615        // writer
7616        synchronized (mPackages) {
7617            if (pkg.mSharedUserId != null) {
7618                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7619                if (suid == null) {
7620                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7621                            "Creating application package " + pkg.packageName
7622                            + " for shared user failed");
7623                }
7624                if (DEBUG_PACKAGE_SCANNING) {
7625                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7626                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7627                                + "): packages=" + suid.packages);
7628                }
7629            }
7630
7631            // Check if we are renaming from an original package name.
7632            PackageSetting origPackage = null;
7633            String realName = null;
7634            if (pkg.mOriginalPackages != null) {
7635                // This package may need to be renamed to a previously
7636                // installed name.  Let's check on that...
7637                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7638                if (pkg.mOriginalPackages.contains(renamed)) {
7639                    // This package had originally been installed as the
7640                    // original name, and we have already taken care of
7641                    // transitioning to the new one.  Just update the new
7642                    // one to continue using the old name.
7643                    realName = pkg.mRealPackage;
7644                    if (!pkg.packageName.equals(renamed)) {
7645                        // Callers into this function may have already taken
7646                        // care of renaming the package; only do it here if
7647                        // it is not already done.
7648                        pkg.setPackageName(renamed);
7649                    }
7650
7651                } else {
7652                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7653                        if ((origPackage = mSettings.peekPackageLPr(
7654                                pkg.mOriginalPackages.get(i))) != null) {
7655                            // We do have the package already installed under its
7656                            // original name...  should we use it?
7657                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7658                                // New package is not compatible with original.
7659                                origPackage = null;
7660                                continue;
7661                            } else if (origPackage.sharedUser != null) {
7662                                // Make sure uid is compatible between packages.
7663                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7664                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7665                                            + " to " + pkg.packageName + ": old uid "
7666                                            + origPackage.sharedUser.name
7667                                            + " differs from " + pkg.mSharedUserId);
7668                                    origPackage = null;
7669                                    continue;
7670                                }
7671                            } else {
7672                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7673                                        + pkg.packageName + " to old name " + origPackage.name);
7674                            }
7675                            break;
7676                        }
7677                    }
7678                }
7679            }
7680
7681            if (mTransferedPackages.contains(pkg.packageName)) {
7682                Slog.w(TAG, "Package " + pkg.packageName
7683                        + " was transferred to another, but its .apk remains");
7684            }
7685
7686            // See comments in nonMutatedPs declaration
7687            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7688                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7689                if (foundPs != null) {
7690                    nonMutatedPs = new PackageSetting(foundPs);
7691                }
7692            }
7693
7694            // Just create the setting, don't add it yet. For already existing packages
7695            // the PkgSetting exists already and doesn't have to be created.
7696            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7697                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7698                    pkg.applicationInfo.primaryCpuAbi,
7699                    pkg.applicationInfo.secondaryCpuAbi,
7700                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7701                    user, false);
7702            if (pkgSetting == null) {
7703                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7704                        "Creating application package " + pkg.packageName + " failed");
7705            }
7706
7707            if (pkgSetting.origPackage != null) {
7708                // If we are first transitioning from an original package,
7709                // fix up the new package's name now.  We need to do this after
7710                // looking up the package under its new name, so getPackageLP
7711                // can take care of fiddling things correctly.
7712                pkg.setPackageName(origPackage.name);
7713
7714                // File a report about this.
7715                String msg = "New package " + pkgSetting.realName
7716                        + " renamed to replace old package " + pkgSetting.name;
7717                reportSettingsProblem(Log.WARN, msg);
7718
7719                // Make a note of it.
7720                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7721                    mTransferedPackages.add(origPackage.name);
7722                }
7723
7724                // No longer need to retain this.
7725                pkgSetting.origPackage = null;
7726            }
7727
7728            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7729                // Make a note of it.
7730                mTransferedPackages.add(pkg.packageName);
7731            }
7732
7733            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7734                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7735            }
7736
7737            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7738                // Check all shared libraries and map to their actual file path.
7739                // We only do this here for apps not on a system dir, because those
7740                // are the only ones that can fail an install due to this.  We
7741                // will take care of the system apps by updating all of their
7742                // library paths after the scan is done.
7743                updateSharedLibrariesLPw(pkg, null);
7744            }
7745
7746            if (mFoundPolicyFile) {
7747                SELinuxMMAC.assignSeinfoValue(pkg);
7748            }
7749
7750            pkg.applicationInfo.uid = pkgSetting.appId;
7751            pkg.mExtras = pkgSetting;
7752            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7753                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7754                    // We just determined the app is signed correctly, so bring
7755                    // over the latest parsed certs.
7756                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7757                } else {
7758                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7759                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7760                                "Package " + pkg.packageName + " upgrade keys do not match the "
7761                                + "previously installed version");
7762                    } else {
7763                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7764                        String msg = "System package " + pkg.packageName
7765                            + " signature changed; retaining data.";
7766                        reportSettingsProblem(Log.WARN, msg);
7767                    }
7768                }
7769            } else {
7770                try {
7771                    verifySignaturesLP(pkgSetting, pkg);
7772                    // We just determined the app is signed correctly, so bring
7773                    // over the latest parsed certs.
7774                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7775                } catch (PackageManagerException e) {
7776                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7777                        throw e;
7778                    }
7779                    // The signature has changed, but this package is in the system
7780                    // image...  let's recover!
7781                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7782                    // However...  if this package is part of a shared user, but it
7783                    // doesn't match the signature of the shared user, let's fail.
7784                    // What this means is that you can't change the signatures
7785                    // associated with an overall shared user, which doesn't seem all
7786                    // that unreasonable.
7787                    if (pkgSetting.sharedUser != null) {
7788                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7789                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7790                            throw new PackageManagerException(
7791                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7792                                            "Signature mismatch for shared user: "
7793                                            + pkgSetting.sharedUser);
7794                        }
7795                    }
7796                    // File a report about this.
7797                    String msg = "System package " + pkg.packageName
7798                        + " signature changed; retaining data.";
7799                    reportSettingsProblem(Log.WARN, msg);
7800                }
7801            }
7802            // Verify that this new package doesn't have any content providers
7803            // that conflict with existing packages.  Only do this if the
7804            // package isn't already installed, since we don't want to break
7805            // things that are installed.
7806            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7807                final int N = pkg.providers.size();
7808                int i;
7809                for (i=0; i<N; i++) {
7810                    PackageParser.Provider p = pkg.providers.get(i);
7811                    if (p.info.authority != null) {
7812                        String names[] = p.info.authority.split(";");
7813                        for (int j = 0; j < names.length; j++) {
7814                            if (mProvidersByAuthority.containsKey(names[j])) {
7815                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7816                                final String otherPackageName =
7817                                        ((other != null && other.getComponentName() != null) ?
7818                                                other.getComponentName().getPackageName() : "?");
7819                                throw new PackageManagerException(
7820                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7821                                                "Can't install because provider name " + names[j]
7822                                                + " (in package " + pkg.applicationInfo.packageName
7823                                                + ") is already used by " + otherPackageName);
7824                            }
7825                        }
7826                    }
7827                }
7828            }
7829
7830            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7831                // This package wants to adopt ownership of permissions from
7832                // another package.
7833                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7834                    final String origName = pkg.mAdoptPermissions.get(i);
7835                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7836                    if (orig != null) {
7837                        if (verifyPackageUpdateLPr(orig, pkg)) {
7838                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7839                                    + pkg.packageName);
7840                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7841                        }
7842                    }
7843                }
7844            }
7845        }
7846
7847        final String pkgName = pkg.packageName;
7848
7849        final long scanFileTime = scanFile.lastModified();
7850        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7851        pkg.applicationInfo.processName = fixProcessName(
7852                pkg.applicationInfo.packageName,
7853                pkg.applicationInfo.processName,
7854                pkg.applicationInfo.uid);
7855
7856        if (pkg != mPlatformPackage) {
7857            // Get all of our default paths setup
7858            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7859        }
7860
7861        final String path = scanFile.getPath();
7862        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7863
7864        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7865            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7866
7867            // Some system apps still use directory structure for native libraries
7868            // in which case we might end up not detecting abi solely based on apk
7869            // structure. Try to detect abi based on directory structure.
7870            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7871                    pkg.applicationInfo.primaryCpuAbi == null) {
7872                setBundledAppAbisAndRoots(pkg, pkgSetting);
7873                setNativeLibraryPaths(pkg);
7874            }
7875
7876        } else {
7877            if ((scanFlags & SCAN_MOVE) != 0) {
7878                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7879                // but we already have this packages package info in the PackageSetting. We just
7880                // use that and derive the native library path based on the new codepath.
7881                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7882                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7883            }
7884
7885            // Set native library paths again. For moves, the path will be updated based on the
7886            // ABIs we've determined above. For non-moves, the path will be updated based on the
7887            // ABIs we determined during compilation, but the path will depend on the final
7888            // package path (after the rename away from the stage path).
7889            setNativeLibraryPaths(pkg);
7890        }
7891
7892        // This is a special case for the "system" package, where the ABI is
7893        // dictated by the zygote configuration (and init.rc). We should keep track
7894        // of this ABI so that we can deal with "normal" applications that run under
7895        // the same UID correctly.
7896        if (mPlatformPackage == pkg) {
7897            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7898                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7899        }
7900
7901        // If there's a mismatch between the abi-override in the package setting
7902        // and the abiOverride specified for the install. Warn about this because we
7903        // would've already compiled the app without taking the package setting into
7904        // account.
7905        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7906            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7907                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7908                        " for package " + pkg.packageName);
7909            }
7910        }
7911
7912        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7913        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7914        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7915
7916        // Copy the derived override back to the parsed package, so that we can
7917        // update the package settings accordingly.
7918        pkg.cpuAbiOverride = cpuAbiOverride;
7919
7920        if (DEBUG_ABI_SELECTION) {
7921            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7922                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7923                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7924        }
7925
7926        // Push the derived path down into PackageSettings so we know what to
7927        // clean up at uninstall time.
7928        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7929
7930        if (DEBUG_ABI_SELECTION) {
7931            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7932                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7933                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7934        }
7935
7936        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7937            // We don't do this here during boot because we can do it all
7938            // at once after scanning all existing packages.
7939            //
7940            // We also do this *before* we perform dexopt on this package, so that
7941            // we can avoid redundant dexopts, and also to make sure we've got the
7942            // code and package path correct.
7943            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7944                    pkg, true /* boot complete */);
7945        }
7946
7947        if (mFactoryTest && pkg.requestedPermissions.contains(
7948                android.Manifest.permission.FACTORY_TEST)) {
7949            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7950        }
7951
7952        ArrayList<PackageParser.Package> clientLibPkgs = null;
7953
7954        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7955            if (nonMutatedPs != null) {
7956                synchronized (mPackages) {
7957                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7958                }
7959            }
7960            return pkg;
7961        }
7962
7963        // Only privileged apps and updated privileged apps can add child packages.
7964        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7965            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7966                throw new PackageManagerException("Only privileged apps and updated "
7967                        + "privileged apps can add child packages. Ignoring package "
7968                        + pkg.packageName);
7969            }
7970            final int childCount = pkg.childPackages.size();
7971            for (int i = 0; i < childCount; i++) {
7972                PackageParser.Package childPkg = pkg.childPackages.get(i);
7973                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7974                        childPkg.packageName)) {
7975                    throw new PackageManagerException("Cannot override a child package of "
7976                            + "another disabled system app. Ignoring package " + pkg.packageName);
7977                }
7978            }
7979        }
7980
7981        // writer
7982        synchronized (mPackages) {
7983            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7984                // Only system apps can add new shared libraries.
7985                if (pkg.libraryNames != null) {
7986                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7987                        String name = pkg.libraryNames.get(i);
7988                        boolean allowed = false;
7989                        if (pkg.isUpdatedSystemApp()) {
7990                            // New library entries can only be added through the
7991                            // system image.  This is important to get rid of a lot
7992                            // of nasty edge cases: for example if we allowed a non-
7993                            // system update of the app to add a library, then uninstalling
7994                            // the update would make the library go away, and assumptions
7995                            // we made such as through app install filtering would now
7996                            // have allowed apps on the device which aren't compatible
7997                            // with it.  Better to just have the restriction here, be
7998                            // conservative, and create many fewer cases that can negatively
7999                            // impact the user experience.
8000                            final PackageSetting sysPs = mSettings
8001                                    .getDisabledSystemPkgLPr(pkg.packageName);
8002                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8003                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8004                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8005                                        allowed = true;
8006                                        break;
8007                                    }
8008                                }
8009                            }
8010                        } else {
8011                            allowed = true;
8012                        }
8013                        if (allowed) {
8014                            if (!mSharedLibraries.containsKey(name)) {
8015                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8016                            } else if (!name.equals(pkg.packageName)) {
8017                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8018                                        + name + " already exists; skipping");
8019                            }
8020                        } else {
8021                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8022                                    + name + " that is not declared on system image; skipping");
8023                        }
8024                    }
8025                    if ((scanFlags & SCAN_BOOTING) == 0) {
8026                        // If we are not booting, we need to update any applications
8027                        // that are clients of our shared library.  If we are booting,
8028                        // this will all be done once the scan is complete.
8029                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8030                    }
8031                }
8032            }
8033        }
8034
8035        // Request the ActivityManager to kill the process(only for existing packages)
8036        // so that we do not end up in a confused state while the user is still using the older
8037        // version of the application while the new one gets installed.
8038        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
8039        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
8040        if (killApp) {
8041            if (isReplacing) {
8042                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
8043
8044                killApplication(pkg.applicationInfo.packageName,
8045                            pkg.applicationInfo.uid, "replace pkg");
8046
8047                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8048            }
8049        }
8050
8051        // Also need to kill any apps that are dependent on the library.
8052        if (clientLibPkgs != null) {
8053            for (int i=0; i<clientLibPkgs.size(); i++) {
8054                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8055                killApplication(clientPkg.applicationInfo.packageName,
8056                        clientPkg.applicationInfo.uid, "update lib");
8057            }
8058        }
8059
8060        // Make sure we're not adding any bogus keyset info
8061        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8062        ksms.assertScannedPackageValid(pkg);
8063
8064        // writer
8065        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8066
8067        boolean createIdmapFailed = false;
8068        synchronized (mPackages) {
8069            // We don't expect installation to fail beyond this point
8070
8071            // Add the new setting to mSettings
8072            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8073            // Add the new setting to mPackages
8074            mPackages.put(pkg.applicationInfo.packageName, pkg);
8075            // Make sure we don't accidentally delete its data.
8076            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8077            while (iter.hasNext()) {
8078                PackageCleanItem item = iter.next();
8079                if (pkgName.equals(item.packageName)) {
8080                    iter.remove();
8081                }
8082            }
8083
8084            // Take care of first install / last update times.
8085            if (currentTime != 0) {
8086                if (pkgSetting.firstInstallTime == 0) {
8087                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8088                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8089                    pkgSetting.lastUpdateTime = currentTime;
8090                }
8091            } else if (pkgSetting.firstInstallTime == 0) {
8092                // We need *something*.  Take time time stamp of the file.
8093                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8094            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8095                if (scanFileTime != pkgSetting.timeStamp) {
8096                    // A package on the system image has changed; consider this
8097                    // to be an update.
8098                    pkgSetting.lastUpdateTime = scanFileTime;
8099                }
8100            }
8101
8102            // Add the package's KeySets to the global KeySetManagerService
8103            ksms.addScannedPackageLPw(pkg);
8104
8105            int N = pkg.providers.size();
8106            StringBuilder r = null;
8107            int i;
8108            for (i=0; i<N; i++) {
8109                PackageParser.Provider p = pkg.providers.get(i);
8110                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8111                        p.info.processName, pkg.applicationInfo.uid);
8112                mProviders.addProvider(p);
8113                p.syncable = p.info.isSyncable;
8114                if (p.info.authority != null) {
8115                    String names[] = p.info.authority.split(";");
8116                    p.info.authority = null;
8117                    for (int j = 0; j < names.length; j++) {
8118                        if (j == 1 && p.syncable) {
8119                            // We only want the first authority for a provider to possibly be
8120                            // syncable, so if we already added this provider using a different
8121                            // authority clear the syncable flag. We copy the provider before
8122                            // changing it because the mProviders object contains a reference
8123                            // to a provider that we don't want to change.
8124                            // Only do this for the second authority since the resulting provider
8125                            // object can be the same for all future authorities for this provider.
8126                            p = new PackageParser.Provider(p);
8127                            p.syncable = false;
8128                        }
8129                        if (!mProvidersByAuthority.containsKey(names[j])) {
8130                            mProvidersByAuthority.put(names[j], p);
8131                            if (p.info.authority == null) {
8132                                p.info.authority = names[j];
8133                            } else {
8134                                p.info.authority = p.info.authority + ";" + names[j];
8135                            }
8136                            if (DEBUG_PACKAGE_SCANNING) {
8137                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8138                                    Log.d(TAG, "Registered content provider: " + names[j]
8139                                            + ", className = " + p.info.name + ", isSyncable = "
8140                                            + p.info.isSyncable);
8141                            }
8142                        } else {
8143                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8144                            Slog.w(TAG, "Skipping provider name " + names[j] +
8145                                    " (in package " + pkg.applicationInfo.packageName +
8146                                    "): name already used by "
8147                                    + ((other != null && other.getComponentName() != null)
8148                                            ? other.getComponentName().getPackageName() : "?"));
8149                        }
8150                    }
8151                }
8152                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8153                    if (r == null) {
8154                        r = new StringBuilder(256);
8155                    } else {
8156                        r.append(' ');
8157                    }
8158                    r.append(p.info.name);
8159                }
8160            }
8161            if (r != null) {
8162                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8163            }
8164
8165            N = pkg.services.size();
8166            r = null;
8167            for (i=0; i<N; i++) {
8168                PackageParser.Service s = pkg.services.get(i);
8169                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8170                        s.info.processName, pkg.applicationInfo.uid);
8171                mServices.addService(s);
8172                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8173                    if (r == null) {
8174                        r = new StringBuilder(256);
8175                    } else {
8176                        r.append(' ');
8177                    }
8178                    r.append(s.info.name);
8179                }
8180            }
8181            if (r != null) {
8182                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8183            }
8184
8185            N = pkg.receivers.size();
8186            r = null;
8187            for (i=0; i<N; i++) {
8188                PackageParser.Activity a = pkg.receivers.get(i);
8189                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8190                        a.info.processName, pkg.applicationInfo.uid);
8191                mReceivers.addActivity(a, "receiver");
8192                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8193                    if (r == null) {
8194                        r = new StringBuilder(256);
8195                    } else {
8196                        r.append(' ');
8197                    }
8198                    r.append(a.info.name);
8199                }
8200            }
8201            if (r != null) {
8202                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8203            }
8204
8205            N = pkg.activities.size();
8206            r = null;
8207            for (i=0; i<N; i++) {
8208                PackageParser.Activity a = pkg.activities.get(i);
8209                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8210                        a.info.processName, pkg.applicationInfo.uid);
8211                mActivities.addActivity(a, "activity");
8212                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8213                    if (r == null) {
8214                        r = new StringBuilder(256);
8215                    } else {
8216                        r.append(' ');
8217                    }
8218                    r.append(a.info.name);
8219                }
8220            }
8221            if (r != null) {
8222                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8223            }
8224
8225            N = pkg.permissionGroups.size();
8226            r = null;
8227            for (i=0; i<N; i++) {
8228                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8229                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8230                if (cur == null) {
8231                    mPermissionGroups.put(pg.info.name, pg);
8232                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8233                        if (r == null) {
8234                            r = new StringBuilder(256);
8235                        } else {
8236                            r.append(' ');
8237                        }
8238                        r.append(pg.info.name);
8239                    }
8240                } else {
8241                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8242                            + pg.info.packageName + " ignored: original from "
8243                            + cur.info.packageName);
8244                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8245                        if (r == null) {
8246                            r = new StringBuilder(256);
8247                        } else {
8248                            r.append(' ');
8249                        }
8250                        r.append("DUP:");
8251                        r.append(pg.info.name);
8252                    }
8253                }
8254            }
8255            if (r != null) {
8256                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8257            }
8258
8259            N = pkg.permissions.size();
8260            r = null;
8261            for (i=0; i<N; i++) {
8262                PackageParser.Permission p = pkg.permissions.get(i);
8263
8264                // Assume by default that we did not install this permission into the system.
8265                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8266
8267                // Now that permission groups have a special meaning, we ignore permission
8268                // groups for legacy apps to prevent unexpected behavior. In particular,
8269                // permissions for one app being granted to someone just becase they happen
8270                // to be in a group defined by another app (before this had no implications).
8271                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8272                    p.group = mPermissionGroups.get(p.info.group);
8273                    // Warn for a permission in an unknown group.
8274                    if (p.info.group != null && p.group == null) {
8275                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8276                                + p.info.packageName + " in an unknown group " + p.info.group);
8277                    }
8278                }
8279
8280                ArrayMap<String, BasePermission> permissionMap =
8281                        p.tree ? mSettings.mPermissionTrees
8282                                : mSettings.mPermissions;
8283                BasePermission bp = permissionMap.get(p.info.name);
8284
8285                // Allow system apps to redefine non-system permissions
8286                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8287                    final boolean currentOwnerIsSystem = (bp.perm != null
8288                            && isSystemApp(bp.perm.owner));
8289                    if (isSystemApp(p.owner)) {
8290                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8291                            // It's a built-in permission and no owner, take ownership now
8292                            bp.packageSetting = pkgSetting;
8293                            bp.perm = p;
8294                            bp.uid = pkg.applicationInfo.uid;
8295                            bp.sourcePackage = p.info.packageName;
8296                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8297                        } else if (!currentOwnerIsSystem) {
8298                            String msg = "New decl " + p.owner + " of permission  "
8299                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8300                            reportSettingsProblem(Log.WARN, msg);
8301                            bp = null;
8302                        }
8303                    }
8304                }
8305
8306                if (bp == null) {
8307                    bp = new BasePermission(p.info.name, p.info.packageName,
8308                            BasePermission.TYPE_NORMAL);
8309                    permissionMap.put(p.info.name, bp);
8310                }
8311
8312                if (bp.perm == null) {
8313                    if (bp.sourcePackage == null
8314                            || bp.sourcePackage.equals(p.info.packageName)) {
8315                        BasePermission tree = findPermissionTreeLP(p.info.name);
8316                        if (tree == null
8317                                || tree.sourcePackage.equals(p.info.packageName)) {
8318                            bp.packageSetting = pkgSetting;
8319                            bp.perm = p;
8320                            bp.uid = pkg.applicationInfo.uid;
8321                            bp.sourcePackage = p.info.packageName;
8322                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8323                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8324                                if (r == null) {
8325                                    r = new StringBuilder(256);
8326                                } else {
8327                                    r.append(' ');
8328                                }
8329                                r.append(p.info.name);
8330                            }
8331                        } else {
8332                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8333                                    + p.info.packageName + " ignored: base tree "
8334                                    + tree.name + " is from package "
8335                                    + tree.sourcePackage);
8336                        }
8337                    } else {
8338                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8339                                + p.info.packageName + " ignored: original from "
8340                                + bp.sourcePackage);
8341                    }
8342                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8343                    if (r == null) {
8344                        r = new StringBuilder(256);
8345                    } else {
8346                        r.append(' ');
8347                    }
8348                    r.append("DUP:");
8349                    r.append(p.info.name);
8350                }
8351                if (bp.perm == p) {
8352                    bp.protectionLevel = p.info.protectionLevel;
8353                }
8354            }
8355
8356            if (r != null) {
8357                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8358            }
8359
8360            N = pkg.instrumentation.size();
8361            r = null;
8362            for (i=0; i<N; i++) {
8363                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8364                a.info.packageName = pkg.applicationInfo.packageName;
8365                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8366                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8367                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8368                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8369                a.info.dataDir = pkg.applicationInfo.dataDir;
8370                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8371                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8372
8373                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8374                // need other information about the application, like the ABI and what not ?
8375                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8376                mInstrumentation.put(a.getComponentName(), a);
8377                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8378                    if (r == null) {
8379                        r = new StringBuilder(256);
8380                    } else {
8381                        r.append(' ');
8382                    }
8383                    r.append(a.info.name);
8384                }
8385            }
8386            if (r != null) {
8387                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8388            }
8389
8390            if (pkg.protectedBroadcasts != null) {
8391                N = pkg.protectedBroadcasts.size();
8392                for (i=0; i<N; i++) {
8393                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8394                }
8395            }
8396
8397            pkgSetting.setTimeStamp(scanFileTime);
8398
8399            // Create idmap files for pairs of (packages, overlay packages).
8400            // Note: "android", ie framework-res.apk, is handled by native layers.
8401            if (pkg.mOverlayTarget != null) {
8402                // This is an overlay package.
8403                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8404                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8405                        mOverlays.put(pkg.mOverlayTarget,
8406                                new ArrayMap<String, PackageParser.Package>());
8407                    }
8408                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8409                    map.put(pkg.packageName, pkg);
8410                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8411                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8412                        createIdmapFailed = true;
8413                    }
8414                }
8415            } else if (mOverlays.containsKey(pkg.packageName) &&
8416                    !pkg.packageName.equals("android")) {
8417                // This is a regular package, with one or more known overlay packages.
8418                createIdmapsForPackageLI(pkg);
8419            }
8420        }
8421
8422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8423
8424        if (createIdmapFailed) {
8425            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8426                    "scanPackageLI failed to createIdmap");
8427        }
8428        return pkg;
8429    }
8430
8431    /**
8432     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8433     * is derived purely on the basis of the contents of {@code scanFile} and
8434     * {@code cpuAbiOverride}.
8435     *
8436     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8437     */
8438    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8439                                 String cpuAbiOverride, boolean extractLibs)
8440            throws PackageManagerException {
8441        // TODO: We can probably be smarter about this stuff. For installed apps,
8442        // we can calculate this information at install time once and for all. For
8443        // system apps, we can probably assume that this information doesn't change
8444        // after the first boot scan. As things stand, we do lots of unnecessary work.
8445
8446        // Give ourselves some initial paths; we'll come back for another
8447        // pass once we've determined ABI below.
8448        setNativeLibraryPaths(pkg);
8449
8450        // We would never need to extract libs for forward-locked and external packages,
8451        // since the container service will do it for us. We shouldn't attempt to
8452        // extract libs from system app when it was not updated.
8453        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8454                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8455            extractLibs = false;
8456        }
8457
8458        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8459        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8460
8461        NativeLibraryHelper.Handle handle = null;
8462        try {
8463            handle = NativeLibraryHelper.Handle.create(pkg);
8464            // TODO(multiArch): This can be null for apps that didn't go through the
8465            // usual installation process. We can calculate it again, like we
8466            // do during install time.
8467            //
8468            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8469            // unnecessary.
8470            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8471
8472            // Null out the abis so that they can be recalculated.
8473            pkg.applicationInfo.primaryCpuAbi = null;
8474            pkg.applicationInfo.secondaryCpuAbi = null;
8475            if (isMultiArch(pkg.applicationInfo)) {
8476                // Warn if we've set an abiOverride for multi-lib packages..
8477                // By definition, we need to copy both 32 and 64 bit libraries for
8478                // such packages.
8479                if (pkg.cpuAbiOverride != null
8480                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8481                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8482                }
8483
8484                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8485                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8486                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8487                    if (extractLibs) {
8488                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8489                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8490                                useIsaSpecificSubdirs);
8491                    } else {
8492                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8493                    }
8494                }
8495
8496                maybeThrowExceptionForMultiArchCopy(
8497                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8498
8499                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8500                    if (extractLibs) {
8501                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8502                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8503                                useIsaSpecificSubdirs);
8504                    } else {
8505                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8506                    }
8507                }
8508
8509                maybeThrowExceptionForMultiArchCopy(
8510                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8511
8512                if (abi64 >= 0) {
8513                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8514                }
8515
8516                if (abi32 >= 0) {
8517                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8518                    if (abi64 >= 0) {
8519                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8520                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8521                            pkg.applicationInfo.primaryCpuAbi = abi;
8522                        } else {
8523                            pkg.applicationInfo.secondaryCpuAbi = abi;
8524                        }
8525                    } else {
8526                        pkg.applicationInfo.primaryCpuAbi = abi;
8527                    }
8528                }
8529
8530            } else {
8531                String[] abiList = (cpuAbiOverride != null) ?
8532                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8533
8534                // Enable gross and lame hacks for apps that are built with old
8535                // SDK tools. We must scan their APKs for renderscript bitcode and
8536                // not launch them if it's present. Don't bother checking on devices
8537                // that don't have 64 bit support.
8538                boolean needsRenderScriptOverride = false;
8539                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8540                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8541                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8542                    needsRenderScriptOverride = true;
8543                }
8544
8545                final int copyRet;
8546                if (extractLibs) {
8547                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8548                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8549                } else {
8550                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8551                }
8552
8553                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8554                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8555                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8556                }
8557
8558                if (copyRet >= 0) {
8559                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8560                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8561                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8562                } else if (needsRenderScriptOverride) {
8563                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8564                }
8565            }
8566        } catch (IOException ioe) {
8567            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8568        } finally {
8569            IoUtils.closeQuietly(handle);
8570        }
8571
8572        // Now that we've calculated the ABIs and determined if it's an internal app,
8573        // we will go ahead and populate the nativeLibraryPath.
8574        setNativeLibraryPaths(pkg);
8575    }
8576
8577    /**
8578     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8579     * i.e, so that all packages can be run inside a single process if required.
8580     *
8581     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8582     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8583     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8584     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8585     * updating a package that belongs to a shared user.
8586     *
8587     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8588     * adds unnecessary complexity.
8589     */
8590    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8591            PackageParser.Package scannedPackage, boolean bootComplete) {
8592        String requiredInstructionSet = null;
8593        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8594            requiredInstructionSet = VMRuntime.getInstructionSet(
8595                     scannedPackage.applicationInfo.primaryCpuAbi);
8596        }
8597
8598        PackageSetting requirer = null;
8599        for (PackageSetting ps : packagesForUser) {
8600            // If packagesForUser contains scannedPackage, we skip it. This will happen
8601            // when scannedPackage is an update of an existing package. Without this check,
8602            // we will never be able to change the ABI of any package belonging to a shared
8603            // user, even if it's compatible with other packages.
8604            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8605                if (ps.primaryCpuAbiString == null) {
8606                    continue;
8607                }
8608
8609                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8610                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8611                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8612                    // this but there's not much we can do.
8613                    String errorMessage = "Instruction set mismatch, "
8614                            + ((requirer == null) ? "[caller]" : requirer)
8615                            + " requires " + requiredInstructionSet + " whereas " + ps
8616                            + " requires " + instructionSet;
8617                    Slog.w(TAG, errorMessage);
8618                }
8619
8620                if (requiredInstructionSet == null) {
8621                    requiredInstructionSet = instructionSet;
8622                    requirer = ps;
8623                }
8624            }
8625        }
8626
8627        if (requiredInstructionSet != null) {
8628            String adjustedAbi;
8629            if (requirer != null) {
8630                // requirer != null implies that either scannedPackage was null or that scannedPackage
8631                // did not require an ABI, in which case we have to adjust scannedPackage to match
8632                // the ABI of the set (which is the same as requirer's ABI)
8633                adjustedAbi = requirer.primaryCpuAbiString;
8634                if (scannedPackage != null) {
8635                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8636                }
8637            } else {
8638                // requirer == null implies that we're updating all ABIs in the set to
8639                // match scannedPackage.
8640                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8641            }
8642
8643            for (PackageSetting ps : packagesForUser) {
8644                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8645                    if (ps.primaryCpuAbiString != null) {
8646                        continue;
8647                    }
8648
8649                    ps.primaryCpuAbiString = adjustedAbi;
8650                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8651                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8652                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8653                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8654                                + " (requirer="
8655                                + (requirer == null ? "null" : requirer.pkg.packageName)
8656                                + ", scannedPackage="
8657                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8658                                + ")");
8659                        try {
8660                            mInstaller.rmdex(ps.codePathString,
8661                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8662                        } catch (InstallerException ignored) {
8663                        }
8664                    }
8665                }
8666            }
8667        }
8668    }
8669
8670    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8671        synchronized (mPackages) {
8672            mResolverReplaced = true;
8673            // Set up information for custom user intent resolution activity.
8674            mResolveActivity.applicationInfo = pkg.applicationInfo;
8675            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8676            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8677            mResolveActivity.processName = pkg.applicationInfo.packageName;
8678            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8679            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8680                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8681            mResolveActivity.theme = 0;
8682            mResolveActivity.exported = true;
8683            mResolveActivity.enabled = true;
8684            mResolveInfo.activityInfo = mResolveActivity;
8685            mResolveInfo.priority = 0;
8686            mResolveInfo.preferredOrder = 0;
8687            mResolveInfo.match = 0;
8688            mResolveComponentName = mCustomResolverComponentName;
8689            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8690                    mResolveComponentName);
8691        }
8692    }
8693
8694    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8695        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8696
8697        // Set up information for ephemeral installer activity
8698        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8699        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8700        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8701        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8702        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8703        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8704                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8705        mEphemeralInstallerActivity.theme = 0;
8706        mEphemeralInstallerActivity.exported = true;
8707        mEphemeralInstallerActivity.enabled = true;
8708        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8709        mEphemeralInstallerInfo.priority = 0;
8710        mEphemeralInstallerInfo.preferredOrder = 0;
8711        mEphemeralInstallerInfo.match = 0;
8712
8713        if (DEBUG_EPHEMERAL) {
8714            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8715        }
8716    }
8717
8718    private static String calculateBundledApkRoot(final String codePathString) {
8719        final File codePath = new File(codePathString);
8720        final File codeRoot;
8721        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8722            codeRoot = Environment.getRootDirectory();
8723        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8724            codeRoot = Environment.getOemDirectory();
8725        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8726            codeRoot = Environment.getVendorDirectory();
8727        } else {
8728            // Unrecognized code path; take its top real segment as the apk root:
8729            // e.g. /something/app/blah.apk => /something
8730            try {
8731                File f = codePath.getCanonicalFile();
8732                File parent = f.getParentFile();    // non-null because codePath is a file
8733                File tmp;
8734                while ((tmp = parent.getParentFile()) != null) {
8735                    f = parent;
8736                    parent = tmp;
8737                }
8738                codeRoot = f;
8739                Slog.w(TAG, "Unrecognized code path "
8740                        + codePath + " - using " + codeRoot);
8741            } catch (IOException e) {
8742                // Can't canonicalize the code path -- shenanigans?
8743                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8744                return Environment.getRootDirectory().getPath();
8745            }
8746        }
8747        return codeRoot.getPath();
8748    }
8749
8750    /**
8751     * Derive and set the location of native libraries for the given package,
8752     * which varies depending on where and how the package was installed.
8753     */
8754    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8755        final ApplicationInfo info = pkg.applicationInfo;
8756        final String codePath = pkg.codePath;
8757        final File codeFile = new File(codePath);
8758        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8759        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8760
8761        info.nativeLibraryRootDir = null;
8762        info.nativeLibraryRootRequiresIsa = false;
8763        info.nativeLibraryDir = null;
8764        info.secondaryNativeLibraryDir = null;
8765
8766        if (isApkFile(codeFile)) {
8767            // Monolithic install
8768            if (bundledApp) {
8769                // If "/system/lib64/apkname" exists, assume that is the per-package
8770                // native library directory to use; otherwise use "/system/lib/apkname".
8771                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8772                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8773                        getPrimaryInstructionSet(info));
8774
8775                // This is a bundled system app so choose the path based on the ABI.
8776                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8777                // is just the default path.
8778                final String apkName = deriveCodePathName(codePath);
8779                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8780                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8781                        apkName).getAbsolutePath();
8782
8783                if (info.secondaryCpuAbi != null) {
8784                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8785                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8786                            secondaryLibDir, apkName).getAbsolutePath();
8787                }
8788            } else if (asecApp) {
8789                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8790                        .getAbsolutePath();
8791            } else {
8792                final String apkName = deriveCodePathName(codePath);
8793                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8794                        .getAbsolutePath();
8795            }
8796
8797            info.nativeLibraryRootRequiresIsa = false;
8798            info.nativeLibraryDir = info.nativeLibraryRootDir;
8799        } else {
8800            // Cluster install
8801            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8802            info.nativeLibraryRootRequiresIsa = true;
8803
8804            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8805                    getPrimaryInstructionSet(info)).getAbsolutePath();
8806
8807            if (info.secondaryCpuAbi != null) {
8808                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8809                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8810            }
8811        }
8812    }
8813
8814    /**
8815     * Calculate the abis and roots for a bundled app. These can uniquely
8816     * be determined from the contents of the system partition, i.e whether
8817     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8818     * of this information, and instead assume that the system was built
8819     * sensibly.
8820     */
8821    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8822                                           PackageSetting pkgSetting) {
8823        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8824
8825        // If "/system/lib64/apkname" exists, assume that is the per-package
8826        // native library directory to use; otherwise use "/system/lib/apkname".
8827        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8828        setBundledAppAbi(pkg, apkRoot, apkName);
8829        // pkgSetting might be null during rescan following uninstall of updates
8830        // to a bundled app, so accommodate that possibility.  The settings in
8831        // that case will be established later from the parsed package.
8832        //
8833        // If the settings aren't null, sync them up with what we've just derived.
8834        // note that apkRoot isn't stored in the package settings.
8835        if (pkgSetting != null) {
8836            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8837            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8838        }
8839    }
8840
8841    /**
8842     * Deduces the ABI of a bundled app and sets the relevant fields on the
8843     * parsed pkg object.
8844     *
8845     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8846     *        under which system libraries are installed.
8847     * @param apkName the name of the installed package.
8848     */
8849    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8850        final File codeFile = new File(pkg.codePath);
8851
8852        final boolean has64BitLibs;
8853        final boolean has32BitLibs;
8854        if (isApkFile(codeFile)) {
8855            // Monolithic install
8856            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8857            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8858        } else {
8859            // Cluster install
8860            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8861            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8862                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8863                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8864                has64BitLibs = (new File(rootDir, isa)).exists();
8865            } else {
8866                has64BitLibs = false;
8867            }
8868            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8869                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8870                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8871                has32BitLibs = (new File(rootDir, isa)).exists();
8872            } else {
8873                has32BitLibs = false;
8874            }
8875        }
8876
8877        if (has64BitLibs && !has32BitLibs) {
8878            // The package has 64 bit libs, but not 32 bit libs. Its primary
8879            // ABI should be 64 bit. We can safely assume here that the bundled
8880            // native libraries correspond to the most preferred ABI in the list.
8881
8882            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8883            pkg.applicationInfo.secondaryCpuAbi = null;
8884        } else if (has32BitLibs && !has64BitLibs) {
8885            // The package has 32 bit libs but not 64 bit libs. Its primary
8886            // ABI should be 32 bit.
8887
8888            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8889            pkg.applicationInfo.secondaryCpuAbi = null;
8890        } else if (has32BitLibs && has64BitLibs) {
8891            // The application has both 64 and 32 bit bundled libraries. We check
8892            // here that the app declares multiArch support, and warn if it doesn't.
8893            //
8894            // We will be lenient here and record both ABIs. The primary will be the
8895            // ABI that's higher on the list, i.e, a device that's configured to prefer
8896            // 64 bit apps will see a 64 bit primary ABI,
8897
8898            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8899                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8900            }
8901
8902            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8903                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8904                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8905            } else {
8906                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8907                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8908            }
8909        } else {
8910            pkg.applicationInfo.primaryCpuAbi = null;
8911            pkg.applicationInfo.secondaryCpuAbi = null;
8912        }
8913    }
8914
8915    private void killPackage(PackageParser.Package pkg, String reason) {
8916        // Kill the parent package
8917        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8918        // Kill the child packages
8919        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8920        for (int i = 0; i < childCount; i++) {
8921            PackageParser.Package childPkg = pkg.childPackages.get(i);
8922            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8923        }
8924    }
8925
8926    private void killApplication(String pkgName, int appId, String reason) {
8927        // Request the ActivityManager to kill the process(only for existing packages)
8928        // so that we do not end up in a confused state while the user is still using the older
8929        // version of the application while the new one gets installed.
8930        IActivityManager am = ActivityManagerNative.getDefault();
8931        if (am != null) {
8932            try {
8933                am.killApplicationWithAppId(pkgName, appId, reason);
8934            } catch (RemoteException e) {
8935            }
8936        }
8937    }
8938
8939    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8940        // Remove the parent package setting
8941        PackageSetting ps = (PackageSetting) pkg.mExtras;
8942        if (ps != null) {
8943            removePackageLI(ps, chatty);
8944        }
8945        // Remove the child package setting
8946        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8947        for (int i = 0; i < childCount; i++) {
8948            PackageParser.Package childPkg = pkg.childPackages.get(i);
8949            ps = (PackageSetting) childPkg.mExtras;
8950            if (ps != null) {
8951                removePackageLI(ps, chatty);
8952            }
8953        }
8954    }
8955
8956    void removePackageLI(PackageSetting ps, boolean chatty) {
8957        if (DEBUG_INSTALL) {
8958            if (chatty)
8959                Log.d(TAG, "Removing package " + ps.name);
8960        }
8961
8962        // writer
8963        synchronized (mPackages) {
8964            mPackages.remove(ps.name);
8965            final PackageParser.Package pkg = ps.pkg;
8966            if (pkg != null) {
8967                cleanPackageDataStructuresLILPw(pkg, chatty);
8968            }
8969        }
8970    }
8971
8972    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8973        if (DEBUG_INSTALL) {
8974            if (chatty)
8975                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8976        }
8977
8978        // writer
8979        synchronized (mPackages) {
8980            // Remove the parent package
8981            mPackages.remove(pkg.applicationInfo.packageName);
8982            cleanPackageDataStructuresLILPw(pkg, chatty);
8983
8984            // Remove the child packages
8985            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8986            for (int i = 0; i < childCount; i++) {
8987                PackageParser.Package childPkg = pkg.childPackages.get(i);
8988                mPackages.remove(childPkg.applicationInfo.packageName);
8989                cleanPackageDataStructuresLILPw(childPkg, chatty);
8990            }
8991        }
8992    }
8993
8994    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8995        int N = pkg.providers.size();
8996        StringBuilder r = null;
8997        int i;
8998        for (i=0; i<N; i++) {
8999            PackageParser.Provider p = pkg.providers.get(i);
9000            mProviders.removeProvider(p);
9001            if (p.info.authority == null) {
9002
9003                /* There was another ContentProvider with this authority when
9004                 * this app was installed so this authority is null,
9005                 * Ignore it as we don't have to unregister the provider.
9006                 */
9007                continue;
9008            }
9009            String names[] = p.info.authority.split(";");
9010            for (int j = 0; j < names.length; j++) {
9011                if (mProvidersByAuthority.get(names[j]) == p) {
9012                    mProvidersByAuthority.remove(names[j]);
9013                    if (DEBUG_REMOVE) {
9014                        if (chatty)
9015                            Log.d(TAG, "Unregistered content provider: " + names[j]
9016                                    + ", className = " + p.info.name + ", isSyncable = "
9017                                    + p.info.isSyncable);
9018                    }
9019                }
9020            }
9021            if (DEBUG_REMOVE && chatty) {
9022                if (r == null) {
9023                    r = new StringBuilder(256);
9024                } else {
9025                    r.append(' ');
9026                }
9027                r.append(p.info.name);
9028            }
9029        }
9030        if (r != null) {
9031            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9032        }
9033
9034        N = pkg.services.size();
9035        r = null;
9036        for (i=0; i<N; i++) {
9037            PackageParser.Service s = pkg.services.get(i);
9038            mServices.removeService(s);
9039            if (chatty) {
9040                if (r == null) {
9041                    r = new StringBuilder(256);
9042                } else {
9043                    r.append(' ');
9044                }
9045                r.append(s.info.name);
9046            }
9047        }
9048        if (r != null) {
9049            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9050        }
9051
9052        N = pkg.receivers.size();
9053        r = null;
9054        for (i=0; i<N; i++) {
9055            PackageParser.Activity a = pkg.receivers.get(i);
9056            mReceivers.removeActivity(a, "receiver");
9057            if (DEBUG_REMOVE && chatty) {
9058                if (r == null) {
9059                    r = new StringBuilder(256);
9060                } else {
9061                    r.append(' ');
9062                }
9063                r.append(a.info.name);
9064            }
9065        }
9066        if (r != null) {
9067            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9068        }
9069
9070        N = pkg.activities.size();
9071        r = null;
9072        for (i=0; i<N; i++) {
9073            PackageParser.Activity a = pkg.activities.get(i);
9074            mActivities.removeActivity(a, "activity");
9075            if (DEBUG_REMOVE && chatty) {
9076                if (r == null) {
9077                    r = new StringBuilder(256);
9078                } else {
9079                    r.append(' ');
9080                }
9081                r.append(a.info.name);
9082            }
9083        }
9084        if (r != null) {
9085            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9086        }
9087
9088        N = pkg.permissions.size();
9089        r = null;
9090        for (i=0; i<N; i++) {
9091            PackageParser.Permission p = pkg.permissions.get(i);
9092            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9093            if (bp == null) {
9094                bp = mSettings.mPermissionTrees.get(p.info.name);
9095            }
9096            if (bp != null && bp.perm == p) {
9097                bp.perm = null;
9098                if (DEBUG_REMOVE && chatty) {
9099                    if (r == null) {
9100                        r = new StringBuilder(256);
9101                    } else {
9102                        r.append(' ');
9103                    }
9104                    r.append(p.info.name);
9105                }
9106            }
9107            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9108                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9109                if (appOpPkgs != null) {
9110                    appOpPkgs.remove(pkg.packageName);
9111                }
9112            }
9113        }
9114        if (r != null) {
9115            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9116        }
9117
9118        N = pkg.requestedPermissions.size();
9119        r = null;
9120        for (i=0; i<N; i++) {
9121            String perm = pkg.requestedPermissions.get(i);
9122            BasePermission bp = mSettings.mPermissions.get(perm);
9123            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9124                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9125                if (appOpPkgs != null) {
9126                    appOpPkgs.remove(pkg.packageName);
9127                    if (appOpPkgs.isEmpty()) {
9128                        mAppOpPermissionPackages.remove(perm);
9129                    }
9130                }
9131            }
9132        }
9133        if (r != null) {
9134            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9135        }
9136
9137        N = pkg.instrumentation.size();
9138        r = null;
9139        for (i=0; i<N; i++) {
9140            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9141            mInstrumentation.remove(a.getComponentName());
9142            if (DEBUG_REMOVE && chatty) {
9143                if (r == null) {
9144                    r = new StringBuilder(256);
9145                } else {
9146                    r.append(' ');
9147                }
9148                r.append(a.info.name);
9149            }
9150        }
9151        if (r != null) {
9152            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9153        }
9154
9155        r = null;
9156        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9157            // Only system apps can hold shared libraries.
9158            if (pkg.libraryNames != null) {
9159                for (i=0; i<pkg.libraryNames.size(); i++) {
9160                    String name = pkg.libraryNames.get(i);
9161                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9162                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9163                        mSharedLibraries.remove(name);
9164                        if (DEBUG_REMOVE && chatty) {
9165                            if (r == null) {
9166                                r = new StringBuilder(256);
9167                            } else {
9168                                r.append(' ');
9169                            }
9170                            r.append(name);
9171                        }
9172                    }
9173                }
9174            }
9175        }
9176        if (r != null) {
9177            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9178        }
9179    }
9180
9181    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9182        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9183            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9184                return true;
9185            }
9186        }
9187        return false;
9188    }
9189
9190    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9191    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9192    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9193
9194    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9195        // Update the parent permissions
9196        updatePermissionsLPw(pkg.packageName, pkg, flags);
9197        // Update the child permissions
9198        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9199        for (int i = 0; i < childCount; i++) {
9200            PackageParser.Package childPkg = pkg.childPackages.get(i);
9201            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9202        }
9203    }
9204
9205    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9206            int flags) {
9207        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9208        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9209    }
9210
9211    private void updatePermissionsLPw(String changingPkg,
9212            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9213        // Make sure there are no dangling permission trees.
9214        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9215        while (it.hasNext()) {
9216            final BasePermission bp = it.next();
9217            if (bp.packageSetting == null) {
9218                // We may not yet have parsed the package, so just see if
9219                // we still know about its settings.
9220                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9221            }
9222            if (bp.packageSetting == null) {
9223                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9224                        + " from package " + bp.sourcePackage);
9225                it.remove();
9226            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9227                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9228                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9229                            + " from package " + bp.sourcePackage);
9230                    flags |= UPDATE_PERMISSIONS_ALL;
9231                    it.remove();
9232                }
9233            }
9234        }
9235
9236        // Make sure all dynamic permissions have been assigned to a package,
9237        // and make sure there are no dangling permissions.
9238        it = mSettings.mPermissions.values().iterator();
9239        while (it.hasNext()) {
9240            final BasePermission bp = it.next();
9241            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9242                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9243                        + bp.name + " pkg=" + bp.sourcePackage
9244                        + " info=" + bp.pendingInfo);
9245                if (bp.packageSetting == null && bp.pendingInfo != null) {
9246                    final BasePermission tree = findPermissionTreeLP(bp.name);
9247                    if (tree != null && tree.perm != null) {
9248                        bp.packageSetting = tree.packageSetting;
9249                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9250                                new PermissionInfo(bp.pendingInfo));
9251                        bp.perm.info.packageName = tree.perm.info.packageName;
9252                        bp.perm.info.name = bp.name;
9253                        bp.uid = tree.uid;
9254                    }
9255                }
9256            }
9257            if (bp.packageSetting == null) {
9258                // We may not yet have parsed the package, so just see if
9259                // we still know about its settings.
9260                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9261            }
9262            if (bp.packageSetting == null) {
9263                Slog.w(TAG, "Removing dangling permission: " + bp.name
9264                        + " from package " + bp.sourcePackage);
9265                it.remove();
9266            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9267                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9268                    Slog.i(TAG, "Removing old permission: " + bp.name
9269                            + " from package " + bp.sourcePackage);
9270                    flags |= UPDATE_PERMISSIONS_ALL;
9271                    it.remove();
9272                }
9273            }
9274        }
9275
9276        // Now update the permissions for all packages, in particular
9277        // replace the granted permissions of the system packages.
9278        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9279            for (PackageParser.Package pkg : mPackages.values()) {
9280                if (pkg != pkgInfo) {
9281                    // Only replace for packages on requested volume
9282                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9283                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9284                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9285                    grantPermissionsLPw(pkg, replace, changingPkg);
9286                }
9287            }
9288        }
9289
9290        if (pkgInfo != null) {
9291            // Only replace for packages on requested volume
9292            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9293            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9294                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9295            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9296        }
9297    }
9298
9299    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9300            String packageOfInterest) {
9301        // IMPORTANT: There are two types of permissions: install and runtime.
9302        // Install time permissions are granted when the app is installed to
9303        // all device users and users added in the future. Runtime permissions
9304        // are granted at runtime explicitly to specific users. Normal and signature
9305        // protected permissions are install time permissions. Dangerous permissions
9306        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9307        // otherwise they are runtime permissions. This function does not manage
9308        // runtime permissions except for the case an app targeting Lollipop MR1
9309        // being upgraded to target a newer SDK, in which case dangerous permissions
9310        // are transformed from install time to runtime ones.
9311
9312        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9313        if (ps == null) {
9314            return;
9315        }
9316
9317        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9318
9319        PermissionsState permissionsState = ps.getPermissionsState();
9320        PermissionsState origPermissions = permissionsState;
9321
9322        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9323
9324        boolean runtimePermissionsRevoked = false;
9325        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9326
9327        boolean changedInstallPermission = false;
9328
9329        if (replace) {
9330            ps.installPermissionsFixed = false;
9331            if (!ps.isSharedUser()) {
9332                origPermissions = new PermissionsState(permissionsState);
9333                permissionsState.reset();
9334            } else {
9335                // We need to know only about runtime permission changes since the
9336                // calling code always writes the install permissions state but
9337                // the runtime ones are written only if changed. The only cases of
9338                // changed runtime permissions here are promotion of an install to
9339                // runtime and revocation of a runtime from a shared user.
9340                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9341                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9342                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9343                    runtimePermissionsRevoked = true;
9344                }
9345            }
9346        }
9347
9348        permissionsState.setGlobalGids(mGlobalGids);
9349
9350        final int N = pkg.requestedPermissions.size();
9351        for (int i=0; i<N; i++) {
9352            final String name = pkg.requestedPermissions.get(i);
9353            final BasePermission bp = mSettings.mPermissions.get(name);
9354
9355            if (DEBUG_INSTALL) {
9356                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9357            }
9358
9359            if (bp == null || bp.packageSetting == null) {
9360                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9361                    Slog.w(TAG, "Unknown permission " + name
9362                            + " in package " + pkg.packageName);
9363                }
9364                continue;
9365            }
9366
9367            final String perm = bp.name;
9368            boolean allowedSig = false;
9369            int grant = GRANT_DENIED;
9370
9371            // Keep track of app op permissions.
9372            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9373                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9374                if (pkgs == null) {
9375                    pkgs = new ArraySet<>();
9376                    mAppOpPermissionPackages.put(bp.name, pkgs);
9377                }
9378                pkgs.add(pkg.packageName);
9379            }
9380
9381            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9382            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9383                    >= Build.VERSION_CODES.M;
9384            switch (level) {
9385                case PermissionInfo.PROTECTION_NORMAL: {
9386                    // For all apps normal permissions are install time ones.
9387                    grant = GRANT_INSTALL;
9388                } break;
9389
9390                case PermissionInfo.PROTECTION_DANGEROUS: {
9391                    // If a permission review is required for legacy apps we represent
9392                    // their permissions as always granted runtime ones since we need
9393                    // to keep the review required permission flag per user while an
9394                    // install permission's state is shared across all users.
9395                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9396                        // For legacy apps dangerous permissions are install time ones.
9397                        grant = GRANT_INSTALL;
9398                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9399                        // For legacy apps that became modern, install becomes runtime.
9400                        grant = GRANT_UPGRADE;
9401                    } else if (mPromoteSystemApps
9402                            && isSystemApp(ps)
9403                            && mExistingSystemPackages.contains(ps.name)) {
9404                        // For legacy system apps, install becomes runtime.
9405                        // We cannot check hasInstallPermission() for system apps since those
9406                        // permissions were granted implicitly and not persisted pre-M.
9407                        grant = GRANT_UPGRADE;
9408                    } else {
9409                        // For modern apps keep runtime permissions unchanged.
9410                        grant = GRANT_RUNTIME;
9411                    }
9412                } break;
9413
9414                case PermissionInfo.PROTECTION_SIGNATURE: {
9415                    // For all apps signature permissions are install time ones.
9416                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9417                    if (allowedSig) {
9418                        grant = GRANT_INSTALL;
9419                    }
9420                } break;
9421            }
9422
9423            if (DEBUG_INSTALL) {
9424                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9425            }
9426
9427            if (grant != GRANT_DENIED) {
9428                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9429                    // If this is an existing, non-system package, then
9430                    // we can't add any new permissions to it.
9431                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9432                        // Except...  if this is a permission that was added
9433                        // to the platform (note: need to only do this when
9434                        // updating the platform).
9435                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9436                            grant = GRANT_DENIED;
9437                        }
9438                    }
9439                }
9440
9441                switch (grant) {
9442                    case GRANT_INSTALL: {
9443                        // Revoke this as runtime permission to handle the case of
9444                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9445                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9446                            if (origPermissions.getRuntimePermissionState(
9447                                    bp.name, userId) != null) {
9448                                // Revoke the runtime permission and clear the flags.
9449                                origPermissions.revokeRuntimePermission(bp, userId);
9450                                origPermissions.updatePermissionFlags(bp, userId,
9451                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9452                                // If we revoked a permission permission, we have to write.
9453                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9454                                        changedRuntimePermissionUserIds, userId);
9455                            }
9456                        }
9457                        // Grant an install permission.
9458                        if (permissionsState.grantInstallPermission(bp) !=
9459                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9460                            changedInstallPermission = true;
9461                        }
9462                    } break;
9463
9464                    case GRANT_RUNTIME: {
9465                        // Grant previously granted runtime permissions.
9466                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9467                            PermissionState permissionState = origPermissions
9468                                    .getRuntimePermissionState(bp.name, userId);
9469                            int flags = permissionState != null
9470                                    ? permissionState.getFlags() : 0;
9471                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9472                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9473                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9474                                    // If we cannot put the permission as it was, we have to write.
9475                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9476                                            changedRuntimePermissionUserIds, userId);
9477                                }
9478                                // If the app supports runtime permissions no need for a review.
9479                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9480                                        && appSupportsRuntimePermissions
9481                                        && (flags & PackageManager
9482                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9483                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9484                                    // Since we changed the flags, we have to write.
9485                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9486                                            changedRuntimePermissionUserIds, userId);
9487                                }
9488                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9489                                    && !appSupportsRuntimePermissions) {
9490                                // For legacy apps that need a permission review, every new
9491                                // runtime permission is granted but it is pending a review.
9492                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9493                                    permissionsState.grantRuntimePermission(bp, userId);
9494                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9495                                    // We changed the permission and flags, hence have to write.
9496                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9497                                            changedRuntimePermissionUserIds, userId);
9498                                }
9499                            }
9500                            // Propagate the permission flags.
9501                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9502                        }
9503                    } break;
9504
9505                    case GRANT_UPGRADE: {
9506                        // Grant runtime permissions for a previously held install permission.
9507                        PermissionState permissionState = origPermissions
9508                                .getInstallPermissionState(bp.name);
9509                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9510
9511                        if (origPermissions.revokeInstallPermission(bp)
9512                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9513                            // We will be transferring the permission flags, so clear them.
9514                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9515                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9516                            changedInstallPermission = true;
9517                        }
9518
9519                        // If the permission is not to be promoted to runtime we ignore it and
9520                        // also its other flags as they are not applicable to install permissions.
9521                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9522                            for (int userId : currentUserIds) {
9523                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9524                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9525                                    // Transfer the permission flags.
9526                                    permissionsState.updatePermissionFlags(bp, userId,
9527                                            flags, flags);
9528                                    // If we granted the permission, we have to write.
9529                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9530                                            changedRuntimePermissionUserIds, userId);
9531                                }
9532                            }
9533                        }
9534                    } break;
9535
9536                    default: {
9537                        if (packageOfInterest == null
9538                                || packageOfInterest.equals(pkg.packageName)) {
9539                            Slog.w(TAG, "Not granting permission " + perm
9540                                    + " to package " + pkg.packageName
9541                                    + " because it was previously installed without");
9542                        }
9543                    } break;
9544                }
9545            } else {
9546                if (permissionsState.revokeInstallPermission(bp) !=
9547                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9548                    // Also drop the permission flags.
9549                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9550                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9551                    changedInstallPermission = true;
9552                    Slog.i(TAG, "Un-granting permission " + perm
9553                            + " from package " + pkg.packageName
9554                            + " (protectionLevel=" + bp.protectionLevel
9555                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9556                            + ")");
9557                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9558                    // Don't print warning for app op permissions, since it is fine for them
9559                    // not to be granted, there is a UI for the user to decide.
9560                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9561                        Slog.w(TAG, "Not granting permission " + perm
9562                                + " to package " + pkg.packageName
9563                                + " (protectionLevel=" + bp.protectionLevel
9564                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9565                                + ")");
9566                    }
9567                }
9568            }
9569        }
9570
9571        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9572                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9573            // This is the first that we have heard about this package, so the
9574            // permissions we have now selected are fixed until explicitly
9575            // changed.
9576            ps.installPermissionsFixed = true;
9577        }
9578
9579        // Persist the runtime permissions state for users with changes. If permissions
9580        // were revoked because no app in the shared user declares them we have to
9581        // write synchronously to avoid losing runtime permissions state.
9582        for (int userId : changedRuntimePermissionUserIds) {
9583            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9584        }
9585
9586        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9587    }
9588
9589    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9590        boolean allowed = false;
9591        final int NP = PackageParser.NEW_PERMISSIONS.length;
9592        for (int ip=0; ip<NP; ip++) {
9593            final PackageParser.NewPermissionInfo npi
9594                    = PackageParser.NEW_PERMISSIONS[ip];
9595            if (npi.name.equals(perm)
9596                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9597                allowed = true;
9598                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9599                        + pkg.packageName);
9600                break;
9601            }
9602        }
9603        return allowed;
9604    }
9605
9606    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9607            BasePermission bp, PermissionsState origPermissions) {
9608        boolean allowed;
9609        allowed = (compareSignatures(
9610                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9611                        == PackageManager.SIGNATURE_MATCH)
9612                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9613                        == PackageManager.SIGNATURE_MATCH);
9614        if (!allowed && (bp.protectionLevel
9615                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9616            if (isSystemApp(pkg)) {
9617                // For updated system applications, a system permission
9618                // is granted only if it had been defined by the original application.
9619                if (pkg.isUpdatedSystemApp()) {
9620                    final PackageSetting sysPs = mSettings
9621                            .getDisabledSystemPkgLPr(pkg.packageName);
9622                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9623                        // If the original was granted this permission, we take
9624                        // that grant decision as read and propagate it to the
9625                        // update.
9626                        if (sysPs.isPrivileged()) {
9627                            allowed = true;
9628                        }
9629                    } else {
9630                        // The system apk may have been updated with an older
9631                        // version of the one on the data partition, but which
9632                        // granted a new system permission that it didn't have
9633                        // before.  In this case we do want to allow the app to
9634                        // now get the new permission if the ancestral apk is
9635                        // privileged to get it.
9636                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9637                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9638                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9639                                    allowed = true;
9640                                    break;
9641                                }
9642                            }
9643                        }
9644                        // Also if a privileged parent package on the system image or any of
9645                        // its children requested a privileged permission, the updated child
9646                        // packages can also get the permission.
9647                        if (pkg.parentPackage != null) {
9648                            final PackageSetting disabledSysParentPs = mSettings
9649                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9650                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9651                                    && disabledSysParentPs.isPrivileged()) {
9652                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9653                                    allowed = true;
9654                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9655                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9656                                    for (int i = 0; i < count; i++) {
9657                                        PackageParser.Package disabledSysChildPkg =
9658                                                disabledSysParentPs.pkg.childPackages.get(i);
9659                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9660                                                perm)) {
9661                                            allowed = true;
9662                                            break;
9663                                        }
9664                                    }
9665                                }
9666                            }
9667                        }
9668                    }
9669                } else {
9670                    allowed = isPrivilegedApp(pkg);
9671                }
9672            }
9673        }
9674        if (!allowed) {
9675            if (!allowed && (bp.protectionLevel
9676                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9677                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9678                // If this was a previously normal/dangerous permission that got moved
9679                // to a system permission as part of the runtime permission redesign, then
9680                // we still want to blindly grant it to old apps.
9681                allowed = true;
9682            }
9683            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9684                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9685                // If this permission is to be granted to the system installer and
9686                // this app is an installer, then it gets the permission.
9687                allowed = true;
9688            }
9689            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9690                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9691                // If this permission is to be granted to the system verifier and
9692                // this app is a verifier, then it gets the permission.
9693                allowed = true;
9694            }
9695            if (!allowed && (bp.protectionLevel
9696                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9697                    && isSystemApp(pkg)) {
9698                // Any pre-installed system app is allowed to get this permission.
9699                allowed = true;
9700            }
9701            if (!allowed && (bp.protectionLevel
9702                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9703                // For development permissions, a development permission
9704                // is granted only if it was already granted.
9705                allowed = origPermissions.hasInstallPermission(perm);
9706            }
9707        }
9708        return allowed;
9709    }
9710
9711    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9712        final int permCount = pkg.requestedPermissions.size();
9713        for (int j = 0; j < permCount; j++) {
9714            String requestedPermission = pkg.requestedPermissions.get(j);
9715            if (permission.equals(requestedPermission)) {
9716                return true;
9717            }
9718        }
9719        return false;
9720    }
9721
9722    final class ActivityIntentResolver
9723            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9724        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9725                boolean defaultOnly, int userId) {
9726            if (!sUserManager.exists(userId)) return null;
9727            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9728            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9729        }
9730
9731        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9732                int userId) {
9733            if (!sUserManager.exists(userId)) return null;
9734            mFlags = flags;
9735            return super.queryIntent(intent, resolvedType,
9736                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9737        }
9738
9739        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9740                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9741            if (!sUserManager.exists(userId)) return null;
9742            if (packageActivities == null) {
9743                return null;
9744            }
9745            mFlags = flags;
9746            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9747            final int N = packageActivities.size();
9748            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9749                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9750
9751            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9752            for (int i = 0; i < N; ++i) {
9753                intentFilters = packageActivities.get(i).intents;
9754                if (intentFilters != null && intentFilters.size() > 0) {
9755                    PackageParser.ActivityIntentInfo[] array =
9756                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9757                    intentFilters.toArray(array);
9758                    listCut.add(array);
9759                }
9760            }
9761            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9762        }
9763
9764        public final void addActivity(PackageParser.Activity a, String type) {
9765            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9766            mActivities.put(a.getComponentName(), a);
9767            if (DEBUG_SHOW_INFO)
9768                Log.v(
9769                TAG, "  " + type + " " +
9770                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9771            if (DEBUG_SHOW_INFO)
9772                Log.v(TAG, "    Class=" + a.info.name);
9773            final int NI = a.intents.size();
9774            for (int j=0; j<NI; j++) {
9775                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9776                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9777                    intent.setPriority(0);
9778                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9779                            + a.className + " with priority > 0, forcing to 0");
9780                }
9781                if (DEBUG_SHOW_INFO) {
9782                    Log.v(TAG, "    IntentFilter:");
9783                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9784                }
9785                if (!intent.debugCheck()) {
9786                    Log.w(TAG, "==> For Activity " + a.info.name);
9787                }
9788                addFilter(intent);
9789            }
9790        }
9791
9792        public final void removeActivity(PackageParser.Activity a, String type) {
9793            mActivities.remove(a.getComponentName());
9794            if (DEBUG_SHOW_INFO) {
9795                Log.v(TAG, "  " + type + " "
9796                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9797                                : a.info.name) + ":");
9798                Log.v(TAG, "    Class=" + a.info.name);
9799            }
9800            final int NI = a.intents.size();
9801            for (int j=0; j<NI; j++) {
9802                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9803                if (DEBUG_SHOW_INFO) {
9804                    Log.v(TAG, "    IntentFilter:");
9805                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9806                }
9807                removeFilter(intent);
9808            }
9809        }
9810
9811        @Override
9812        protected boolean allowFilterResult(
9813                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9814            ActivityInfo filterAi = filter.activity.info;
9815            for (int i=dest.size()-1; i>=0; i--) {
9816                ActivityInfo destAi = dest.get(i).activityInfo;
9817                if (destAi.name == filterAi.name
9818                        && destAi.packageName == filterAi.packageName) {
9819                    return false;
9820                }
9821            }
9822            return true;
9823        }
9824
9825        @Override
9826        protected ActivityIntentInfo[] newArray(int size) {
9827            return new ActivityIntentInfo[size];
9828        }
9829
9830        @Override
9831        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9832            if (!sUserManager.exists(userId)) return true;
9833            PackageParser.Package p = filter.activity.owner;
9834            if (p != null) {
9835                PackageSetting ps = (PackageSetting)p.mExtras;
9836                if (ps != null) {
9837                    // System apps are never considered stopped for purposes of
9838                    // filtering, because there may be no way for the user to
9839                    // actually re-launch them.
9840                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9841                            && ps.getStopped(userId);
9842                }
9843            }
9844            return false;
9845        }
9846
9847        @Override
9848        protected boolean isPackageForFilter(String packageName,
9849                PackageParser.ActivityIntentInfo info) {
9850            return packageName.equals(info.activity.owner.packageName);
9851        }
9852
9853        @Override
9854        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9855                int match, int userId) {
9856            if (!sUserManager.exists(userId)) return null;
9857            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9858                return null;
9859            }
9860            final PackageParser.Activity activity = info.activity;
9861            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9862            if (ps == null) {
9863                return null;
9864            }
9865            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9866                    ps.readUserState(userId), userId);
9867            if (ai == null) {
9868                return null;
9869            }
9870            final ResolveInfo res = new ResolveInfo();
9871            res.activityInfo = ai;
9872            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9873                res.filter = info;
9874            }
9875            if (info != null) {
9876                res.handleAllWebDataURI = info.handleAllWebDataURI();
9877            }
9878            res.priority = info.getPriority();
9879            res.preferredOrder = activity.owner.mPreferredOrder;
9880            //System.out.println("Result: " + res.activityInfo.className +
9881            //                   " = " + res.priority);
9882            res.match = match;
9883            res.isDefault = info.hasDefault;
9884            res.labelRes = info.labelRes;
9885            res.nonLocalizedLabel = info.nonLocalizedLabel;
9886            if (userNeedsBadging(userId)) {
9887                res.noResourceId = true;
9888            } else {
9889                res.icon = info.icon;
9890            }
9891            res.iconResourceId = info.icon;
9892            res.system = res.activityInfo.applicationInfo.isSystemApp();
9893            return res;
9894        }
9895
9896        @Override
9897        protected void sortResults(List<ResolveInfo> results) {
9898            Collections.sort(results, mResolvePrioritySorter);
9899        }
9900
9901        @Override
9902        protected void dumpFilter(PrintWriter out, String prefix,
9903                PackageParser.ActivityIntentInfo filter) {
9904            out.print(prefix); out.print(
9905                    Integer.toHexString(System.identityHashCode(filter.activity)));
9906                    out.print(' ');
9907                    filter.activity.printComponentShortName(out);
9908                    out.print(" filter ");
9909                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9910        }
9911
9912        @Override
9913        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9914            return filter.activity;
9915        }
9916
9917        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9918            PackageParser.Activity activity = (PackageParser.Activity)label;
9919            out.print(prefix); out.print(
9920                    Integer.toHexString(System.identityHashCode(activity)));
9921                    out.print(' ');
9922                    activity.printComponentShortName(out);
9923            if (count > 1) {
9924                out.print(" ("); out.print(count); out.print(" filters)");
9925            }
9926            out.println();
9927        }
9928
9929//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9930//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9931//            final List<ResolveInfo> retList = Lists.newArrayList();
9932//            while (i.hasNext()) {
9933//                final ResolveInfo resolveInfo = i.next();
9934//                if (isEnabledLP(resolveInfo.activityInfo)) {
9935//                    retList.add(resolveInfo);
9936//                }
9937//            }
9938//            return retList;
9939//        }
9940
9941        // Keys are String (activity class name), values are Activity.
9942        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9943                = new ArrayMap<ComponentName, PackageParser.Activity>();
9944        private int mFlags;
9945    }
9946
9947    private final class ServiceIntentResolver
9948            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9949        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9950                boolean defaultOnly, int userId) {
9951            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9952            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9953        }
9954
9955        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9956                int userId) {
9957            if (!sUserManager.exists(userId)) return null;
9958            mFlags = flags;
9959            return super.queryIntent(intent, resolvedType,
9960                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9961        }
9962
9963        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9964                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9965            if (!sUserManager.exists(userId)) return null;
9966            if (packageServices == null) {
9967                return null;
9968            }
9969            mFlags = flags;
9970            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9971            final int N = packageServices.size();
9972            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9973                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9974
9975            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9976            for (int i = 0; i < N; ++i) {
9977                intentFilters = packageServices.get(i).intents;
9978                if (intentFilters != null && intentFilters.size() > 0) {
9979                    PackageParser.ServiceIntentInfo[] array =
9980                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9981                    intentFilters.toArray(array);
9982                    listCut.add(array);
9983                }
9984            }
9985            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9986        }
9987
9988        public final void addService(PackageParser.Service s) {
9989            mServices.put(s.getComponentName(), s);
9990            if (DEBUG_SHOW_INFO) {
9991                Log.v(TAG, "  "
9992                        + (s.info.nonLocalizedLabel != null
9993                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9994                Log.v(TAG, "    Class=" + s.info.name);
9995            }
9996            final int NI = s.intents.size();
9997            int j;
9998            for (j=0; j<NI; j++) {
9999                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10000                if (DEBUG_SHOW_INFO) {
10001                    Log.v(TAG, "    IntentFilter:");
10002                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10003                }
10004                if (!intent.debugCheck()) {
10005                    Log.w(TAG, "==> For Service " + s.info.name);
10006                }
10007                addFilter(intent);
10008            }
10009        }
10010
10011        public final void removeService(PackageParser.Service s) {
10012            mServices.remove(s.getComponentName());
10013            if (DEBUG_SHOW_INFO) {
10014                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10015                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10016                Log.v(TAG, "    Class=" + s.info.name);
10017            }
10018            final int NI = s.intents.size();
10019            int j;
10020            for (j=0; j<NI; j++) {
10021                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10022                if (DEBUG_SHOW_INFO) {
10023                    Log.v(TAG, "    IntentFilter:");
10024                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10025                }
10026                removeFilter(intent);
10027            }
10028        }
10029
10030        @Override
10031        protected boolean allowFilterResult(
10032                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10033            ServiceInfo filterSi = filter.service.info;
10034            for (int i=dest.size()-1; i>=0; i--) {
10035                ServiceInfo destAi = dest.get(i).serviceInfo;
10036                if (destAi.name == filterSi.name
10037                        && destAi.packageName == filterSi.packageName) {
10038                    return false;
10039                }
10040            }
10041            return true;
10042        }
10043
10044        @Override
10045        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10046            return new PackageParser.ServiceIntentInfo[size];
10047        }
10048
10049        @Override
10050        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10051            if (!sUserManager.exists(userId)) return true;
10052            PackageParser.Package p = filter.service.owner;
10053            if (p != null) {
10054                PackageSetting ps = (PackageSetting)p.mExtras;
10055                if (ps != null) {
10056                    // System apps are never considered stopped for purposes of
10057                    // filtering, because there may be no way for the user to
10058                    // actually re-launch them.
10059                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10060                            && ps.getStopped(userId);
10061                }
10062            }
10063            return false;
10064        }
10065
10066        @Override
10067        protected boolean isPackageForFilter(String packageName,
10068                PackageParser.ServiceIntentInfo info) {
10069            return packageName.equals(info.service.owner.packageName);
10070        }
10071
10072        @Override
10073        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10074                int match, int userId) {
10075            if (!sUserManager.exists(userId)) return null;
10076            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10077            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10078                return null;
10079            }
10080            final PackageParser.Service service = info.service;
10081            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10082            if (ps == null) {
10083                return null;
10084            }
10085            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10086                    ps.readUserState(userId), userId);
10087            if (si == null) {
10088                return null;
10089            }
10090            final ResolveInfo res = new ResolveInfo();
10091            res.serviceInfo = si;
10092            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10093                res.filter = filter;
10094            }
10095            res.priority = info.getPriority();
10096            res.preferredOrder = service.owner.mPreferredOrder;
10097            res.match = match;
10098            res.isDefault = info.hasDefault;
10099            res.labelRes = info.labelRes;
10100            res.nonLocalizedLabel = info.nonLocalizedLabel;
10101            res.icon = info.icon;
10102            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10103            return res;
10104        }
10105
10106        @Override
10107        protected void sortResults(List<ResolveInfo> results) {
10108            Collections.sort(results, mResolvePrioritySorter);
10109        }
10110
10111        @Override
10112        protected void dumpFilter(PrintWriter out, String prefix,
10113                PackageParser.ServiceIntentInfo filter) {
10114            out.print(prefix); out.print(
10115                    Integer.toHexString(System.identityHashCode(filter.service)));
10116                    out.print(' ');
10117                    filter.service.printComponentShortName(out);
10118                    out.print(" filter ");
10119                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10120        }
10121
10122        @Override
10123        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10124            return filter.service;
10125        }
10126
10127        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10128            PackageParser.Service service = (PackageParser.Service)label;
10129            out.print(prefix); out.print(
10130                    Integer.toHexString(System.identityHashCode(service)));
10131                    out.print(' ');
10132                    service.printComponentShortName(out);
10133            if (count > 1) {
10134                out.print(" ("); out.print(count); out.print(" filters)");
10135            }
10136            out.println();
10137        }
10138
10139//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10140//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10141//            final List<ResolveInfo> retList = Lists.newArrayList();
10142//            while (i.hasNext()) {
10143//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10144//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10145//                    retList.add(resolveInfo);
10146//                }
10147//            }
10148//            return retList;
10149//        }
10150
10151        // Keys are String (activity class name), values are Activity.
10152        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10153                = new ArrayMap<ComponentName, PackageParser.Service>();
10154        private int mFlags;
10155    };
10156
10157    private final class ProviderIntentResolver
10158            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10159        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10160                boolean defaultOnly, int userId) {
10161            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10162            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10163        }
10164
10165        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10166                int userId) {
10167            if (!sUserManager.exists(userId))
10168                return null;
10169            mFlags = flags;
10170            return super.queryIntent(intent, resolvedType,
10171                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10172        }
10173
10174        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10175                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10176            if (!sUserManager.exists(userId))
10177                return null;
10178            if (packageProviders == null) {
10179                return null;
10180            }
10181            mFlags = flags;
10182            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10183            final int N = packageProviders.size();
10184            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10185                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10186
10187            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10188            for (int i = 0; i < N; ++i) {
10189                intentFilters = packageProviders.get(i).intents;
10190                if (intentFilters != null && intentFilters.size() > 0) {
10191                    PackageParser.ProviderIntentInfo[] array =
10192                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10193                    intentFilters.toArray(array);
10194                    listCut.add(array);
10195                }
10196            }
10197            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10198        }
10199
10200        public final void addProvider(PackageParser.Provider p) {
10201            if (mProviders.containsKey(p.getComponentName())) {
10202                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10203                return;
10204            }
10205
10206            mProviders.put(p.getComponentName(), p);
10207            if (DEBUG_SHOW_INFO) {
10208                Log.v(TAG, "  "
10209                        + (p.info.nonLocalizedLabel != null
10210                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10211                Log.v(TAG, "    Class=" + p.info.name);
10212            }
10213            final int NI = p.intents.size();
10214            int j;
10215            for (j = 0; j < NI; j++) {
10216                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10217                if (DEBUG_SHOW_INFO) {
10218                    Log.v(TAG, "    IntentFilter:");
10219                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10220                }
10221                if (!intent.debugCheck()) {
10222                    Log.w(TAG, "==> For Provider " + p.info.name);
10223                }
10224                addFilter(intent);
10225            }
10226        }
10227
10228        public final void removeProvider(PackageParser.Provider p) {
10229            mProviders.remove(p.getComponentName());
10230            if (DEBUG_SHOW_INFO) {
10231                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10232                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10233                Log.v(TAG, "    Class=" + p.info.name);
10234            }
10235            final int NI = p.intents.size();
10236            int j;
10237            for (j = 0; j < NI; j++) {
10238                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10239                if (DEBUG_SHOW_INFO) {
10240                    Log.v(TAG, "    IntentFilter:");
10241                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10242                }
10243                removeFilter(intent);
10244            }
10245        }
10246
10247        @Override
10248        protected boolean allowFilterResult(
10249                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10250            ProviderInfo filterPi = filter.provider.info;
10251            for (int i = dest.size() - 1; i >= 0; i--) {
10252                ProviderInfo destPi = dest.get(i).providerInfo;
10253                if (destPi.name == filterPi.name
10254                        && destPi.packageName == filterPi.packageName) {
10255                    return false;
10256                }
10257            }
10258            return true;
10259        }
10260
10261        @Override
10262        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10263            return new PackageParser.ProviderIntentInfo[size];
10264        }
10265
10266        @Override
10267        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10268            if (!sUserManager.exists(userId))
10269                return true;
10270            PackageParser.Package p = filter.provider.owner;
10271            if (p != null) {
10272                PackageSetting ps = (PackageSetting) p.mExtras;
10273                if (ps != null) {
10274                    // System apps are never considered stopped for purposes of
10275                    // filtering, because there may be no way for the user to
10276                    // actually re-launch them.
10277                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10278                            && ps.getStopped(userId);
10279                }
10280            }
10281            return false;
10282        }
10283
10284        @Override
10285        protected boolean isPackageForFilter(String packageName,
10286                PackageParser.ProviderIntentInfo info) {
10287            return packageName.equals(info.provider.owner.packageName);
10288        }
10289
10290        @Override
10291        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10292                int match, int userId) {
10293            if (!sUserManager.exists(userId))
10294                return null;
10295            final PackageParser.ProviderIntentInfo info = filter;
10296            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10297                return null;
10298            }
10299            final PackageParser.Provider provider = info.provider;
10300            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10301            if (ps == null) {
10302                return null;
10303            }
10304            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10305                    ps.readUserState(userId), userId);
10306            if (pi == null) {
10307                return null;
10308            }
10309            final ResolveInfo res = new ResolveInfo();
10310            res.providerInfo = pi;
10311            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10312                res.filter = filter;
10313            }
10314            res.priority = info.getPriority();
10315            res.preferredOrder = provider.owner.mPreferredOrder;
10316            res.match = match;
10317            res.isDefault = info.hasDefault;
10318            res.labelRes = info.labelRes;
10319            res.nonLocalizedLabel = info.nonLocalizedLabel;
10320            res.icon = info.icon;
10321            res.system = res.providerInfo.applicationInfo.isSystemApp();
10322            return res;
10323        }
10324
10325        @Override
10326        protected void sortResults(List<ResolveInfo> results) {
10327            Collections.sort(results, mResolvePrioritySorter);
10328        }
10329
10330        @Override
10331        protected void dumpFilter(PrintWriter out, String prefix,
10332                PackageParser.ProviderIntentInfo filter) {
10333            out.print(prefix);
10334            out.print(
10335                    Integer.toHexString(System.identityHashCode(filter.provider)));
10336            out.print(' ');
10337            filter.provider.printComponentShortName(out);
10338            out.print(" filter ");
10339            out.println(Integer.toHexString(System.identityHashCode(filter)));
10340        }
10341
10342        @Override
10343        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10344            return filter.provider;
10345        }
10346
10347        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10348            PackageParser.Provider provider = (PackageParser.Provider)label;
10349            out.print(prefix); out.print(
10350                    Integer.toHexString(System.identityHashCode(provider)));
10351                    out.print(' ');
10352                    provider.printComponentShortName(out);
10353            if (count > 1) {
10354                out.print(" ("); out.print(count); out.print(" filters)");
10355            }
10356            out.println();
10357        }
10358
10359        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10360                = new ArrayMap<ComponentName, PackageParser.Provider>();
10361        private int mFlags;
10362    }
10363
10364    private static final class EphemeralIntentResolver
10365            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10366        @Override
10367        protected EphemeralResolveIntentInfo[] newArray(int size) {
10368            return new EphemeralResolveIntentInfo[size];
10369        }
10370
10371        @Override
10372        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10373            return true;
10374        }
10375
10376        @Override
10377        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10378                int userId) {
10379            if (!sUserManager.exists(userId)) {
10380                return null;
10381            }
10382            return info.getEphemeralResolveInfo();
10383        }
10384    }
10385
10386    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10387            new Comparator<ResolveInfo>() {
10388        public int compare(ResolveInfo r1, ResolveInfo r2) {
10389            int v1 = r1.priority;
10390            int v2 = r2.priority;
10391            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10392            if (v1 != v2) {
10393                return (v1 > v2) ? -1 : 1;
10394            }
10395            v1 = r1.preferredOrder;
10396            v2 = r2.preferredOrder;
10397            if (v1 != v2) {
10398                return (v1 > v2) ? -1 : 1;
10399            }
10400            if (r1.isDefault != r2.isDefault) {
10401                return r1.isDefault ? -1 : 1;
10402            }
10403            v1 = r1.match;
10404            v2 = r2.match;
10405            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10406            if (v1 != v2) {
10407                return (v1 > v2) ? -1 : 1;
10408            }
10409            if (r1.system != r2.system) {
10410                return r1.system ? -1 : 1;
10411            }
10412            if (r1.activityInfo != null) {
10413                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10414            }
10415            if (r1.serviceInfo != null) {
10416                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10417            }
10418            if (r1.providerInfo != null) {
10419                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10420            }
10421            return 0;
10422        }
10423    };
10424
10425    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10426            new Comparator<ProviderInfo>() {
10427        public int compare(ProviderInfo p1, ProviderInfo p2) {
10428            final int v1 = p1.initOrder;
10429            final int v2 = p2.initOrder;
10430            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10431        }
10432    };
10433
10434    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10435            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10436            final int[] userIds) {
10437        mHandler.post(new Runnable() {
10438            @Override
10439            public void run() {
10440                try {
10441                    final IActivityManager am = ActivityManagerNative.getDefault();
10442                    if (am == null) return;
10443                    final int[] resolvedUserIds;
10444                    if (userIds == null) {
10445                        resolvedUserIds = am.getRunningUserIds();
10446                    } else {
10447                        resolvedUserIds = userIds;
10448                    }
10449                    for (int id : resolvedUserIds) {
10450                        final Intent intent = new Intent(action,
10451                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10452                        if (extras != null) {
10453                            intent.putExtras(extras);
10454                        }
10455                        if (targetPkg != null) {
10456                            intent.setPackage(targetPkg);
10457                        }
10458                        // Modify the UID when posting to other users
10459                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10460                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10461                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10462                            intent.putExtra(Intent.EXTRA_UID, uid);
10463                        }
10464                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10465                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10466                        if (DEBUG_BROADCASTS) {
10467                            RuntimeException here = new RuntimeException("here");
10468                            here.fillInStackTrace();
10469                            Slog.d(TAG, "Sending to user " + id + ": "
10470                                    + intent.toShortString(false, true, false, false)
10471                                    + " " + intent.getExtras(), here);
10472                        }
10473                        am.broadcastIntent(null, intent, null, finishedReceiver,
10474                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10475                                null, finishedReceiver != null, false, id);
10476                    }
10477                } catch (RemoteException ex) {
10478                }
10479            }
10480        });
10481    }
10482
10483    /**
10484     * Check if the external storage media is available. This is true if there
10485     * is a mounted external storage medium or if the external storage is
10486     * emulated.
10487     */
10488    private boolean isExternalMediaAvailable() {
10489        return mMediaMounted || Environment.isExternalStorageEmulated();
10490    }
10491
10492    @Override
10493    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10494        // writer
10495        synchronized (mPackages) {
10496            if (!isExternalMediaAvailable()) {
10497                // If the external storage is no longer mounted at this point,
10498                // the caller may not have been able to delete all of this
10499                // packages files and can not delete any more.  Bail.
10500                return null;
10501            }
10502            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10503            if (lastPackage != null) {
10504                pkgs.remove(lastPackage);
10505            }
10506            if (pkgs.size() > 0) {
10507                return pkgs.get(0);
10508            }
10509        }
10510        return null;
10511    }
10512
10513    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10514        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10515                userId, andCode ? 1 : 0, packageName);
10516        if (mSystemReady) {
10517            msg.sendToTarget();
10518        } else {
10519            if (mPostSystemReadyMessages == null) {
10520                mPostSystemReadyMessages = new ArrayList<>();
10521            }
10522            mPostSystemReadyMessages.add(msg);
10523        }
10524    }
10525
10526    void startCleaningPackages() {
10527        // reader
10528        if (!isExternalMediaAvailable()) {
10529            return;
10530        }
10531        synchronized (mPackages) {
10532            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10533                return;
10534            }
10535        }
10536        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10537        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10538        IActivityManager am = ActivityManagerNative.getDefault();
10539        if (am != null) {
10540            try {
10541                am.startService(null, intent, null, mContext.getOpPackageName(),
10542                        UserHandle.USER_SYSTEM);
10543            } catch (RemoteException e) {
10544            }
10545        }
10546    }
10547
10548    @Override
10549    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10550            int installFlags, String installerPackageName, int userId) {
10551        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10552
10553        final int callingUid = Binder.getCallingUid();
10554        enforceCrossUserPermission(callingUid, userId,
10555                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10556
10557        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10558            try {
10559                if (observer != null) {
10560                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10561                }
10562            } catch (RemoteException re) {
10563            }
10564            return;
10565        }
10566
10567        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10568            installFlags |= PackageManager.INSTALL_FROM_ADB;
10569
10570        } else {
10571            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10572            // about installerPackageName.
10573
10574            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10575            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10576        }
10577
10578        UserHandle user;
10579        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10580            user = UserHandle.ALL;
10581        } else {
10582            user = new UserHandle(userId);
10583        }
10584
10585        // Only system components can circumvent runtime permissions when installing.
10586        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10587                && mContext.checkCallingOrSelfPermission(Manifest.permission
10588                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10589            throw new SecurityException("You need the "
10590                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10591                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10592        }
10593
10594        final File originFile = new File(originPath);
10595        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10596
10597        final Message msg = mHandler.obtainMessage(INIT_COPY);
10598        final VerificationInfo verificationInfo = new VerificationInfo(
10599                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10600        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10601                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10602                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10603        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10604        msg.obj = params;
10605
10606        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10607                System.identityHashCode(msg.obj));
10608        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10609                System.identityHashCode(msg.obj));
10610
10611        mHandler.sendMessage(msg);
10612    }
10613
10614    void installStage(String packageName, File stagedDir, String stagedCid,
10615            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10616            String installerPackageName, int installerUid, UserHandle user) {
10617        if (DEBUG_EPHEMERAL) {
10618            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10619                Slog.d(TAG, "Ephemeral install of " + packageName);
10620            }
10621        }
10622        final VerificationInfo verificationInfo = new VerificationInfo(
10623                sessionParams.originatingUri, sessionParams.referrerUri,
10624                sessionParams.originatingUid, installerUid);
10625
10626        final OriginInfo origin;
10627        if (stagedDir != null) {
10628            origin = OriginInfo.fromStagedFile(stagedDir);
10629        } else {
10630            origin = OriginInfo.fromStagedContainer(stagedCid);
10631        }
10632
10633        final Message msg = mHandler.obtainMessage(INIT_COPY);
10634        final InstallParams params = new InstallParams(origin, null, observer,
10635                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10636                verificationInfo, user, sessionParams.abiOverride,
10637                sessionParams.grantedRuntimePermissions);
10638        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10639        msg.obj = params;
10640
10641        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10642                System.identityHashCode(msg.obj));
10643        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10644                System.identityHashCode(msg.obj));
10645
10646        mHandler.sendMessage(msg);
10647    }
10648
10649    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10650            int userId) {
10651        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10652        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10653    }
10654
10655    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10656            int appId, int userId) {
10657        Bundle extras = new Bundle(1);
10658        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10659
10660        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10661                packageName, extras, 0, null, null, new int[] {userId});
10662        try {
10663            IActivityManager am = ActivityManagerNative.getDefault();
10664            if (isSystem && am.isUserRunning(userId, 0)) {
10665                // The just-installed/enabled app is bundled on the system, so presumed
10666                // to be able to run automatically without needing an explicit launch.
10667                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10668                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10669                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10670                        .setPackage(packageName);
10671                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10672                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10673            }
10674        } catch (RemoteException e) {
10675            // shouldn't happen
10676            Slog.w(TAG, "Unable to bootstrap installed package", e);
10677        }
10678    }
10679
10680    @Override
10681    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10682            int userId) {
10683        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10684        PackageSetting pkgSetting;
10685        final int uid = Binder.getCallingUid();
10686        enforceCrossUserPermission(uid, userId,
10687                true /* requireFullPermission */, true /* checkShell */,
10688                "setApplicationHiddenSetting for user " + userId);
10689
10690        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10691            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10692            return false;
10693        }
10694
10695        long callingId = Binder.clearCallingIdentity();
10696        try {
10697            boolean sendAdded = false;
10698            boolean sendRemoved = false;
10699            // writer
10700            synchronized (mPackages) {
10701                pkgSetting = mSettings.mPackages.get(packageName);
10702                if (pkgSetting == null) {
10703                    return false;
10704                }
10705                if (pkgSetting.getHidden(userId) != hidden) {
10706                    pkgSetting.setHidden(hidden, userId);
10707                    mSettings.writePackageRestrictionsLPr(userId);
10708                    if (hidden) {
10709                        sendRemoved = true;
10710                    } else {
10711                        sendAdded = true;
10712                    }
10713                }
10714            }
10715            if (sendAdded) {
10716                sendPackageAddedForUser(packageName, pkgSetting, userId);
10717                return true;
10718            }
10719            if (sendRemoved) {
10720                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10721                        "hiding pkg");
10722                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10723                return true;
10724            }
10725        } finally {
10726            Binder.restoreCallingIdentity(callingId);
10727        }
10728        return false;
10729    }
10730
10731    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10732            int userId) {
10733        final PackageRemovedInfo info = new PackageRemovedInfo();
10734        info.removedPackage = packageName;
10735        info.removedUsers = new int[] {userId};
10736        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10737        info.sendPackageRemovedBroadcasts(true /*killApp*/);
10738    }
10739
10740    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10741        if (pkgList.length > 0) {
10742            Bundle extras = new Bundle(1);
10743            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10744
10745            sendPackageBroadcast(
10746                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10747                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10748                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10749                    new int[] {userId});
10750        }
10751    }
10752
10753    /**
10754     * Returns true if application is not found or there was an error. Otherwise it returns
10755     * the hidden state of the package for the given user.
10756     */
10757    @Override
10758    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10759        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10760        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10761                true /* requireFullPermission */, false /* checkShell */,
10762                "getApplicationHidden for user " + userId);
10763        PackageSetting pkgSetting;
10764        long callingId = Binder.clearCallingIdentity();
10765        try {
10766            // writer
10767            synchronized (mPackages) {
10768                pkgSetting = mSettings.mPackages.get(packageName);
10769                if (pkgSetting == null) {
10770                    return true;
10771                }
10772                return pkgSetting.getHidden(userId);
10773            }
10774        } finally {
10775            Binder.restoreCallingIdentity(callingId);
10776        }
10777    }
10778
10779    /**
10780     * @hide
10781     */
10782    @Override
10783    public int installExistingPackageAsUser(String packageName, int userId) {
10784        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10785                null);
10786        PackageSetting pkgSetting;
10787        final int uid = Binder.getCallingUid();
10788        enforceCrossUserPermission(uid, userId,
10789                true /* requireFullPermission */, true /* checkShell */,
10790                "installExistingPackage for user " + userId);
10791        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10792            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10793        }
10794
10795        long callingId = Binder.clearCallingIdentity();
10796        try {
10797            boolean installed = false;
10798
10799            // writer
10800            synchronized (mPackages) {
10801                pkgSetting = mSettings.mPackages.get(packageName);
10802                if (pkgSetting == null) {
10803                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10804                }
10805                if (!pkgSetting.getInstalled(userId)) {
10806                    pkgSetting.setInstalled(true, userId);
10807                    pkgSetting.setHidden(false, userId);
10808                    mSettings.writePackageRestrictionsLPr(userId);
10809                    installed = true;
10810                }
10811            }
10812
10813            if (installed) {
10814                if (pkgSetting.pkg != null) {
10815                    prepareAppDataAfterInstall(pkgSetting.pkg);
10816                }
10817                sendPackageAddedForUser(packageName, pkgSetting, userId);
10818            }
10819        } finally {
10820            Binder.restoreCallingIdentity(callingId);
10821        }
10822
10823        return PackageManager.INSTALL_SUCCEEDED;
10824    }
10825
10826    boolean isUserRestricted(int userId, String restrictionKey) {
10827        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10828        if (restrictions.getBoolean(restrictionKey, false)) {
10829            Log.w(TAG, "User is restricted: " + restrictionKey);
10830            return true;
10831        }
10832        return false;
10833    }
10834
10835    @Override
10836    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10837            int userId) {
10838        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10839        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10840                true /* requireFullPermission */, true /* checkShell */,
10841                "setPackagesSuspended for user " + userId);
10842
10843        if (ArrayUtils.isEmpty(packageNames)) {
10844            return packageNames;
10845        }
10846
10847        // List of package names for whom the suspended state has changed.
10848        List<String> changedPackages = new ArrayList<>(packageNames.length);
10849        // List of package names for whom the suspended state is not set as requested in this
10850        // method.
10851        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10852        for (int i = 0; i < packageNames.length; i++) {
10853            String packageName = packageNames[i];
10854            long callingId = Binder.clearCallingIdentity();
10855            try {
10856                boolean changed = false;
10857                final int appId;
10858                synchronized (mPackages) {
10859                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10860                    if (pkgSetting == null) {
10861                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10862                                + "\". Skipping suspending/un-suspending.");
10863                        unactionedPackages.add(packageName);
10864                        continue;
10865                    }
10866                    appId = pkgSetting.appId;
10867                    if (pkgSetting.getSuspended(userId) != suspended) {
10868                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
10869                            unactionedPackages.add(packageName);
10870                            continue;
10871                        }
10872                        pkgSetting.setSuspended(suspended, userId);
10873                        mSettings.writePackageRestrictionsLPr(userId);
10874                        changed = true;
10875                        changedPackages.add(packageName);
10876                    }
10877                }
10878
10879                if (changed && suspended) {
10880                    killApplication(packageName, UserHandle.getUid(userId, appId),
10881                            "suspending package");
10882                }
10883            } finally {
10884                Binder.restoreCallingIdentity(callingId);
10885            }
10886        }
10887
10888        if (!changedPackages.isEmpty()) {
10889            sendPackagesSuspendedForUser(changedPackages.toArray(
10890                    new String[changedPackages.size()]), userId, suspended);
10891        }
10892
10893        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10894    }
10895
10896    @Override
10897    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10898        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10899                true /* requireFullPermission */, false /* checkShell */,
10900                "isPackageSuspendedForUser for user " + userId);
10901        synchronized (mPackages) {
10902            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10903            return pkgSetting != null && pkgSetting.getSuspended(userId);
10904        }
10905    }
10906
10907    /**
10908     * TODO: cache and disallow blocking the active dialer.
10909     *
10910     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
10911     */
10912    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
10913        if (isPackageDeviceAdmin(packageName, userId)) {
10914            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10915                    + "\": has an active device admin");
10916            return false;
10917        }
10918
10919        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10920        if (packageName.equals(activeLauncherPackageName)) {
10921            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10922                    + "\": contains the active launcher");
10923            return false;
10924        }
10925
10926        if (packageName.equals(mRequiredInstallerPackage)) {
10927            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10928                    + "\": required for package installation");
10929            return false;
10930        }
10931
10932        if (packageName.equals(mRequiredVerifierPackage)) {
10933            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10934                    + "\": required for package verification");
10935            return false;
10936        }
10937
10938        final PackageParser.Package pkg = mPackages.get(packageName);
10939        if (pkg != null && isPrivilegedApp(pkg)) {
10940            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10941                    + "\": is a privileged app");
10942            return false;
10943        }
10944
10945        return true;
10946    }
10947
10948    private String getActiveLauncherPackageName(int userId) {
10949        Intent intent = new Intent(Intent.ACTION_MAIN);
10950        intent.addCategory(Intent.CATEGORY_HOME);
10951        ResolveInfo resolveInfo = resolveIntent(
10952                intent,
10953                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10954                PackageManager.MATCH_DEFAULT_ONLY,
10955                userId);
10956
10957        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10958    }
10959
10960    @Override
10961    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10962        mContext.enforceCallingOrSelfPermission(
10963                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10964                "Only package verification agents can verify applications");
10965
10966        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10967        final PackageVerificationResponse response = new PackageVerificationResponse(
10968                verificationCode, Binder.getCallingUid());
10969        msg.arg1 = id;
10970        msg.obj = response;
10971        mHandler.sendMessage(msg);
10972    }
10973
10974    @Override
10975    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10976            long millisecondsToDelay) {
10977        mContext.enforceCallingOrSelfPermission(
10978                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10979                "Only package verification agents can extend verification timeouts");
10980
10981        final PackageVerificationState state = mPendingVerification.get(id);
10982        final PackageVerificationResponse response = new PackageVerificationResponse(
10983                verificationCodeAtTimeout, Binder.getCallingUid());
10984
10985        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10986            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10987        }
10988        if (millisecondsToDelay < 0) {
10989            millisecondsToDelay = 0;
10990        }
10991        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10992                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10993            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10994        }
10995
10996        if ((state != null) && !state.timeoutExtended()) {
10997            state.extendTimeout();
10998
10999            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11000            msg.arg1 = id;
11001            msg.obj = response;
11002            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11003        }
11004    }
11005
11006    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11007            int verificationCode, UserHandle user) {
11008        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11009        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11010        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11011        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11012        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11013
11014        mContext.sendBroadcastAsUser(intent, user,
11015                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11016    }
11017
11018    private ComponentName matchComponentForVerifier(String packageName,
11019            List<ResolveInfo> receivers) {
11020        ActivityInfo targetReceiver = null;
11021
11022        final int NR = receivers.size();
11023        for (int i = 0; i < NR; i++) {
11024            final ResolveInfo info = receivers.get(i);
11025            if (info.activityInfo == null) {
11026                continue;
11027            }
11028
11029            if (packageName.equals(info.activityInfo.packageName)) {
11030                targetReceiver = info.activityInfo;
11031                break;
11032            }
11033        }
11034
11035        if (targetReceiver == null) {
11036            return null;
11037        }
11038
11039        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11040    }
11041
11042    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11043            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11044        if (pkgInfo.verifiers.length == 0) {
11045            return null;
11046        }
11047
11048        final int N = pkgInfo.verifiers.length;
11049        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11050        for (int i = 0; i < N; i++) {
11051            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11052
11053            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11054                    receivers);
11055            if (comp == null) {
11056                continue;
11057            }
11058
11059            final int verifierUid = getUidForVerifier(verifierInfo);
11060            if (verifierUid == -1) {
11061                continue;
11062            }
11063
11064            if (DEBUG_VERIFY) {
11065                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11066                        + " with the correct signature");
11067            }
11068            sufficientVerifiers.add(comp);
11069            verificationState.addSufficientVerifier(verifierUid);
11070        }
11071
11072        return sufficientVerifiers;
11073    }
11074
11075    private int getUidForVerifier(VerifierInfo verifierInfo) {
11076        synchronized (mPackages) {
11077            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11078            if (pkg == null) {
11079                return -1;
11080            } else if (pkg.mSignatures.length != 1) {
11081                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11082                        + " has more than one signature; ignoring");
11083                return -1;
11084            }
11085
11086            /*
11087             * If the public key of the package's signature does not match
11088             * our expected public key, then this is a different package and
11089             * we should skip.
11090             */
11091
11092            final byte[] expectedPublicKey;
11093            try {
11094                final Signature verifierSig = pkg.mSignatures[0];
11095                final PublicKey publicKey = verifierSig.getPublicKey();
11096                expectedPublicKey = publicKey.getEncoded();
11097            } catch (CertificateException e) {
11098                return -1;
11099            }
11100
11101            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11102
11103            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11104                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11105                        + " does not have the expected public key; ignoring");
11106                return -1;
11107            }
11108
11109            return pkg.applicationInfo.uid;
11110        }
11111    }
11112
11113    @Override
11114    public void finishPackageInstall(int token) {
11115        enforceSystemOrRoot("Only the system is allowed to finish installs");
11116
11117        if (DEBUG_INSTALL) {
11118            Slog.v(TAG, "BM finishing package install for " + token);
11119        }
11120        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11121
11122        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11123        mHandler.sendMessage(msg);
11124    }
11125
11126    /**
11127     * Get the verification agent timeout.
11128     *
11129     * @return verification timeout in milliseconds
11130     */
11131    private long getVerificationTimeout() {
11132        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11133                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11134                DEFAULT_VERIFICATION_TIMEOUT);
11135    }
11136
11137    /**
11138     * Get the default verification agent response code.
11139     *
11140     * @return default verification response code
11141     */
11142    private int getDefaultVerificationResponse() {
11143        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11144                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11145                DEFAULT_VERIFICATION_RESPONSE);
11146    }
11147
11148    /**
11149     * Check whether or not package verification has been enabled.
11150     *
11151     * @return true if verification should be performed
11152     */
11153    private boolean isVerificationEnabled(int userId, int installFlags) {
11154        if (!DEFAULT_VERIFY_ENABLE) {
11155            return false;
11156        }
11157        // Ephemeral apps don't get the full verification treatment
11158        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11159            if (DEBUG_EPHEMERAL) {
11160                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11161            }
11162            return false;
11163        }
11164
11165        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11166
11167        // Check if installing from ADB
11168        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11169            // Do not run verification in a test harness environment
11170            if (ActivityManager.isRunningInTestHarness()) {
11171                return false;
11172            }
11173            if (ensureVerifyAppsEnabled) {
11174                return true;
11175            }
11176            // Check if the developer does not want package verification for ADB installs
11177            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11178                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11179                return false;
11180            }
11181        }
11182
11183        if (ensureVerifyAppsEnabled) {
11184            return true;
11185        }
11186
11187        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11188                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11189    }
11190
11191    @Override
11192    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11193            throws RemoteException {
11194        mContext.enforceCallingOrSelfPermission(
11195                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11196                "Only intentfilter verification agents can verify applications");
11197
11198        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11199        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11200                Binder.getCallingUid(), verificationCode, failedDomains);
11201        msg.arg1 = id;
11202        msg.obj = response;
11203        mHandler.sendMessage(msg);
11204    }
11205
11206    @Override
11207    public int getIntentVerificationStatus(String packageName, int userId) {
11208        synchronized (mPackages) {
11209            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11210        }
11211    }
11212
11213    @Override
11214    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11215        mContext.enforceCallingOrSelfPermission(
11216                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11217
11218        boolean result = false;
11219        synchronized (mPackages) {
11220            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11221        }
11222        if (result) {
11223            scheduleWritePackageRestrictionsLocked(userId);
11224        }
11225        return result;
11226    }
11227
11228    @Override
11229    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11230            String packageName) {
11231        synchronized (mPackages) {
11232            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11233        }
11234    }
11235
11236    @Override
11237    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11238        if (TextUtils.isEmpty(packageName)) {
11239            return ParceledListSlice.emptyList();
11240        }
11241        synchronized (mPackages) {
11242            PackageParser.Package pkg = mPackages.get(packageName);
11243            if (pkg == null || pkg.activities == null) {
11244                return ParceledListSlice.emptyList();
11245            }
11246            final int count = pkg.activities.size();
11247            ArrayList<IntentFilter> result = new ArrayList<>();
11248            for (int n=0; n<count; n++) {
11249                PackageParser.Activity activity = pkg.activities.get(n);
11250                if (activity.intents != null && activity.intents.size() > 0) {
11251                    result.addAll(activity.intents);
11252                }
11253            }
11254            return new ParceledListSlice<>(result);
11255        }
11256    }
11257
11258    @Override
11259    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11260        mContext.enforceCallingOrSelfPermission(
11261                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11262
11263        synchronized (mPackages) {
11264            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11265            if (packageName != null) {
11266                result |= updateIntentVerificationStatus(packageName,
11267                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11268                        userId);
11269                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11270                        packageName, userId);
11271            }
11272            return result;
11273        }
11274    }
11275
11276    @Override
11277    public String getDefaultBrowserPackageName(int userId) {
11278        synchronized (mPackages) {
11279            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11280        }
11281    }
11282
11283    /**
11284     * Get the "allow unknown sources" setting.
11285     *
11286     * @return the current "allow unknown sources" setting
11287     */
11288    private int getUnknownSourcesSettings() {
11289        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11290                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11291                -1);
11292    }
11293
11294    @Override
11295    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11296        final int uid = Binder.getCallingUid();
11297        // writer
11298        synchronized (mPackages) {
11299            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11300            if (targetPackageSetting == null) {
11301                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11302            }
11303
11304            PackageSetting installerPackageSetting;
11305            if (installerPackageName != null) {
11306                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11307                if (installerPackageSetting == null) {
11308                    throw new IllegalArgumentException("Unknown installer package: "
11309                            + installerPackageName);
11310                }
11311            } else {
11312                installerPackageSetting = null;
11313            }
11314
11315            Signature[] callerSignature;
11316            Object obj = mSettings.getUserIdLPr(uid);
11317            if (obj != null) {
11318                if (obj instanceof SharedUserSetting) {
11319                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11320                } else if (obj instanceof PackageSetting) {
11321                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11322                } else {
11323                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11324                }
11325            } else {
11326                throw new SecurityException("Unknown calling UID: " + uid);
11327            }
11328
11329            // Verify: can't set installerPackageName to a package that is
11330            // not signed with the same cert as the caller.
11331            if (installerPackageSetting != null) {
11332                if (compareSignatures(callerSignature,
11333                        installerPackageSetting.signatures.mSignatures)
11334                        != PackageManager.SIGNATURE_MATCH) {
11335                    throw new SecurityException(
11336                            "Caller does not have same cert as new installer package "
11337                            + installerPackageName);
11338                }
11339            }
11340
11341            // Verify: if target already has an installer package, it must
11342            // be signed with the same cert as the caller.
11343            if (targetPackageSetting.installerPackageName != null) {
11344                PackageSetting setting = mSettings.mPackages.get(
11345                        targetPackageSetting.installerPackageName);
11346                // If the currently set package isn't valid, then it's always
11347                // okay to change it.
11348                if (setting != null) {
11349                    if (compareSignatures(callerSignature,
11350                            setting.signatures.mSignatures)
11351                            != PackageManager.SIGNATURE_MATCH) {
11352                        throw new SecurityException(
11353                                "Caller does not have same cert as old installer package "
11354                                + targetPackageSetting.installerPackageName);
11355                    }
11356                }
11357            }
11358
11359            // Okay!
11360            targetPackageSetting.installerPackageName = installerPackageName;
11361            scheduleWriteSettingsLocked();
11362        }
11363    }
11364
11365    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11366        // Queue up an async operation since the package installation may take a little while.
11367        mHandler.post(new Runnable() {
11368            public void run() {
11369                mHandler.removeCallbacks(this);
11370                 // Result object to be returned
11371                PackageInstalledInfo res = new PackageInstalledInfo();
11372                res.setReturnCode(currentStatus);
11373                res.uid = -1;
11374                res.pkg = null;
11375                res.removedInfo = null;
11376                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11377                    args.doPreInstall(res.returnCode);
11378                    synchronized (mInstallLock) {
11379                        installPackageTracedLI(args, res);
11380                    }
11381                    args.doPostInstall(res.returnCode, res.uid);
11382                }
11383
11384                // A restore should be performed at this point if (a) the install
11385                // succeeded, (b) the operation is not an update, and (c) the new
11386                // package has not opted out of backup participation.
11387                final boolean update = res.removedInfo != null
11388                        && res.removedInfo.removedPackage != null;
11389                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11390                boolean doRestore = !update
11391                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11392
11393                // Set up the post-install work request bookkeeping.  This will be used
11394                // and cleaned up by the post-install event handling regardless of whether
11395                // there's a restore pass performed.  Token values are >= 1.
11396                int token;
11397                if (mNextInstallToken < 0) mNextInstallToken = 1;
11398                token = mNextInstallToken++;
11399
11400                PostInstallData data = new PostInstallData(args, res);
11401                mRunningInstalls.put(token, data);
11402                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11403
11404                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11405                    // Pass responsibility to the Backup Manager.  It will perform a
11406                    // restore if appropriate, then pass responsibility back to the
11407                    // Package Manager to run the post-install observer callbacks
11408                    // and broadcasts.
11409                    IBackupManager bm = IBackupManager.Stub.asInterface(
11410                            ServiceManager.getService(Context.BACKUP_SERVICE));
11411                    if (bm != null) {
11412                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11413                                + " to BM for possible restore");
11414                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11415                        try {
11416                            // TODO: http://b/22388012
11417                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11418                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11419                            } else {
11420                                doRestore = false;
11421                            }
11422                        } catch (RemoteException e) {
11423                            // can't happen; the backup manager is local
11424                        } catch (Exception e) {
11425                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11426                            doRestore = false;
11427                        }
11428                    } else {
11429                        Slog.e(TAG, "Backup Manager not found!");
11430                        doRestore = false;
11431                    }
11432                }
11433
11434                if (!doRestore) {
11435                    // No restore possible, or the Backup Manager was mysteriously not
11436                    // available -- just fire the post-install work request directly.
11437                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11438
11439                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11440
11441                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11442                    mHandler.sendMessage(msg);
11443                }
11444            }
11445        });
11446    }
11447
11448    private abstract class HandlerParams {
11449        private static final int MAX_RETRIES = 4;
11450
11451        /**
11452         * Number of times startCopy() has been attempted and had a non-fatal
11453         * error.
11454         */
11455        private int mRetries = 0;
11456
11457        /** User handle for the user requesting the information or installation. */
11458        private final UserHandle mUser;
11459        String traceMethod;
11460        int traceCookie;
11461
11462        HandlerParams(UserHandle user) {
11463            mUser = user;
11464        }
11465
11466        UserHandle getUser() {
11467            return mUser;
11468        }
11469
11470        HandlerParams setTraceMethod(String traceMethod) {
11471            this.traceMethod = traceMethod;
11472            return this;
11473        }
11474
11475        HandlerParams setTraceCookie(int traceCookie) {
11476            this.traceCookie = traceCookie;
11477            return this;
11478        }
11479
11480        final boolean startCopy() {
11481            boolean res;
11482            try {
11483                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11484
11485                if (++mRetries > MAX_RETRIES) {
11486                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11487                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11488                    handleServiceError();
11489                    return false;
11490                } else {
11491                    handleStartCopy();
11492                    res = true;
11493                }
11494            } catch (RemoteException e) {
11495                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11496                mHandler.sendEmptyMessage(MCS_RECONNECT);
11497                res = false;
11498            }
11499            handleReturnCode();
11500            return res;
11501        }
11502
11503        final void serviceError() {
11504            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11505            handleServiceError();
11506            handleReturnCode();
11507        }
11508
11509        abstract void handleStartCopy() throws RemoteException;
11510        abstract void handleServiceError();
11511        abstract void handleReturnCode();
11512    }
11513
11514    class MeasureParams extends HandlerParams {
11515        private final PackageStats mStats;
11516        private boolean mSuccess;
11517
11518        private final IPackageStatsObserver mObserver;
11519
11520        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11521            super(new UserHandle(stats.userHandle));
11522            mObserver = observer;
11523            mStats = stats;
11524        }
11525
11526        @Override
11527        public String toString() {
11528            return "MeasureParams{"
11529                + Integer.toHexString(System.identityHashCode(this))
11530                + " " + mStats.packageName + "}";
11531        }
11532
11533        @Override
11534        void handleStartCopy() throws RemoteException {
11535            synchronized (mInstallLock) {
11536                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11537            }
11538
11539            if (mSuccess) {
11540                final boolean mounted;
11541                if (Environment.isExternalStorageEmulated()) {
11542                    mounted = true;
11543                } else {
11544                    final String status = Environment.getExternalStorageState();
11545                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11546                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11547                }
11548
11549                if (mounted) {
11550                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11551
11552                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11553                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11554
11555                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11556                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11557
11558                    // Always subtract cache size, since it's a subdirectory
11559                    mStats.externalDataSize -= mStats.externalCacheSize;
11560
11561                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11562                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11563
11564                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11565                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11566                }
11567            }
11568        }
11569
11570        @Override
11571        void handleReturnCode() {
11572            if (mObserver != null) {
11573                try {
11574                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11575                } catch (RemoteException e) {
11576                    Slog.i(TAG, "Observer no longer exists.");
11577                }
11578            }
11579        }
11580
11581        @Override
11582        void handleServiceError() {
11583            Slog.e(TAG, "Could not measure application " + mStats.packageName
11584                            + " external storage");
11585        }
11586    }
11587
11588    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11589            throws RemoteException {
11590        long result = 0;
11591        for (File path : paths) {
11592            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11593        }
11594        return result;
11595    }
11596
11597    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11598        for (File path : paths) {
11599            try {
11600                mcs.clearDirectory(path.getAbsolutePath());
11601            } catch (RemoteException e) {
11602            }
11603        }
11604    }
11605
11606    static class OriginInfo {
11607        /**
11608         * Location where install is coming from, before it has been
11609         * copied/renamed into place. This could be a single monolithic APK
11610         * file, or a cluster directory. This location may be untrusted.
11611         */
11612        final File file;
11613        final String cid;
11614
11615        /**
11616         * Flag indicating that {@link #file} or {@link #cid} has already been
11617         * staged, meaning downstream users don't need to defensively copy the
11618         * contents.
11619         */
11620        final boolean staged;
11621
11622        /**
11623         * Flag indicating that {@link #file} or {@link #cid} is an already
11624         * installed app that is being moved.
11625         */
11626        final boolean existing;
11627
11628        final String resolvedPath;
11629        final File resolvedFile;
11630
11631        static OriginInfo fromNothing() {
11632            return new OriginInfo(null, null, false, false);
11633        }
11634
11635        static OriginInfo fromUntrustedFile(File file) {
11636            return new OriginInfo(file, null, false, false);
11637        }
11638
11639        static OriginInfo fromExistingFile(File file) {
11640            return new OriginInfo(file, null, false, true);
11641        }
11642
11643        static OriginInfo fromStagedFile(File file) {
11644            return new OriginInfo(file, null, true, false);
11645        }
11646
11647        static OriginInfo fromStagedContainer(String cid) {
11648            return new OriginInfo(null, cid, true, false);
11649        }
11650
11651        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11652            this.file = file;
11653            this.cid = cid;
11654            this.staged = staged;
11655            this.existing = existing;
11656
11657            if (cid != null) {
11658                resolvedPath = PackageHelper.getSdDir(cid);
11659                resolvedFile = new File(resolvedPath);
11660            } else if (file != null) {
11661                resolvedPath = file.getAbsolutePath();
11662                resolvedFile = file;
11663            } else {
11664                resolvedPath = null;
11665                resolvedFile = null;
11666            }
11667        }
11668    }
11669
11670    static class MoveInfo {
11671        final int moveId;
11672        final String fromUuid;
11673        final String toUuid;
11674        final String packageName;
11675        final String dataAppName;
11676        final int appId;
11677        final String seinfo;
11678        final int targetSdkVersion;
11679
11680        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11681                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11682            this.moveId = moveId;
11683            this.fromUuid = fromUuid;
11684            this.toUuid = toUuid;
11685            this.packageName = packageName;
11686            this.dataAppName = dataAppName;
11687            this.appId = appId;
11688            this.seinfo = seinfo;
11689            this.targetSdkVersion = targetSdkVersion;
11690        }
11691    }
11692
11693    static class VerificationInfo {
11694        /** A constant used to indicate that a uid value is not present. */
11695        public static final int NO_UID = -1;
11696
11697        /** URI referencing where the package was downloaded from. */
11698        final Uri originatingUri;
11699
11700        /** HTTP referrer URI associated with the originatingURI. */
11701        final Uri referrer;
11702
11703        /** UID of the application that the install request originated from. */
11704        final int originatingUid;
11705
11706        /** UID of application requesting the install */
11707        final int installerUid;
11708
11709        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11710            this.originatingUri = originatingUri;
11711            this.referrer = referrer;
11712            this.originatingUid = originatingUid;
11713            this.installerUid = installerUid;
11714        }
11715    }
11716
11717    class InstallParams extends HandlerParams {
11718        final OriginInfo origin;
11719        final MoveInfo move;
11720        final IPackageInstallObserver2 observer;
11721        int installFlags;
11722        final String installerPackageName;
11723        final String volumeUuid;
11724        private InstallArgs mArgs;
11725        private int mRet;
11726        final String packageAbiOverride;
11727        final String[] grantedRuntimePermissions;
11728        final VerificationInfo verificationInfo;
11729
11730        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11731                int installFlags, String installerPackageName, String volumeUuid,
11732                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11733                String[] grantedPermissions) {
11734            super(user);
11735            this.origin = origin;
11736            this.move = move;
11737            this.observer = observer;
11738            this.installFlags = installFlags;
11739            this.installerPackageName = installerPackageName;
11740            this.volumeUuid = volumeUuid;
11741            this.verificationInfo = verificationInfo;
11742            this.packageAbiOverride = packageAbiOverride;
11743            this.grantedRuntimePermissions = grantedPermissions;
11744        }
11745
11746        @Override
11747        public String toString() {
11748            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11749                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11750        }
11751
11752        private int installLocationPolicy(PackageInfoLite pkgLite) {
11753            String packageName = pkgLite.packageName;
11754            int installLocation = pkgLite.installLocation;
11755            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11756            // reader
11757            synchronized (mPackages) {
11758                // Currently installed package which the new package is attempting to replace or
11759                // null if no such package is installed.
11760                PackageParser.Package installedPkg = mPackages.get(packageName);
11761                // Package which currently owns the data which the new package will own if installed.
11762                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
11763                // will be null whereas dataOwnerPkg will contain information about the package
11764                // which was uninstalled while keeping its data.
11765                PackageParser.Package dataOwnerPkg = installedPkg;
11766                if (dataOwnerPkg  == null) {
11767                    PackageSetting ps = mSettings.mPackages.get(packageName);
11768                    if (ps != null) {
11769                        dataOwnerPkg = ps.pkg;
11770                    }
11771                }
11772
11773                if (dataOwnerPkg != null) {
11774                    // If installed, the package will get access to data left on the device by its
11775                    // predecessor. As a security measure, this is permited only if this is not a
11776                    // version downgrade or if the predecessor package is marked as debuggable and
11777                    // a downgrade is explicitly requested.
11778                    if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0)
11779                            || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) {
11780                        try {
11781                            checkDowngrade(dataOwnerPkg, pkgLite);
11782                        } catch (PackageManagerException e) {
11783                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11784                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11785                        }
11786                    }
11787                }
11788
11789                if (installedPkg != null) {
11790                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11791                        // Check for updated system application.
11792                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11793                            if (onSd) {
11794                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11795                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11796                            }
11797                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11798                        } else {
11799                            if (onSd) {
11800                                // Install flag overrides everything.
11801                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11802                            }
11803                            // If current upgrade specifies particular preference
11804                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11805                                // Application explicitly specified internal.
11806                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11807                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11808                                // App explictly prefers external. Let policy decide
11809                            } else {
11810                                // Prefer previous location
11811                                if (isExternal(installedPkg)) {
11812                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11813                                }
11814                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11815                            }
11816                        }
11817                    } else {
11818                        // Invalid install. Return error code
11819                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11820                    }
11821                }
11822            }
11823            // All the special cases have been taken care of.
11824            // Return result based on recommended install location.
11825            if (onSd) {
11826                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11827            }
11828            return pkgLite.recommendedInstallLocation;
11829        }
11830
11831        /*
11832         * Invoke remote method to get package information and install
11833         * location values. Override install location based on default
11834         * policy if needed and then create install arguments based
11835         * on the install location.
11836         */
11837        public void handleStartCopy() throws RemoteException {
11838            int ret = PackageManager.INSTALL_SUCCEEDED;
11839
11840            // If we're already staged, we've firmly committed to an install location
11841            if (origin.staged) {
11842                if (origin.file != null) {
11843                    installFlags |= PackageManager.INSTALL_INTERNAL;
11844                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11845                } else if (origin.cid != null) {
11846                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11847                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11848                } else {
11849                    throw new IllegalStateException("Invalid stage location");
11850                }
11851            }
11852
11853            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11854            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11855            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11856            PackageInfoLite pkgLite = null;
11857
11858            if (onInt && onSd) {
11859                // Check if both bits are set.
11860                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11861                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11862            } else if (onSd && ephemeral) {
11863                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11864                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11865            } else {
11866                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11867                        packageAbiOverride);
11868
11869                if (DEBUG_EPHEMERAL && ephemeral) {
11870                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11871                }
11872
11873                /*
11874                 * If we have too little free space, try to free cache
11875                 * before giving up.
11876                 */
11877                if (!origin.staged && pkgLite.recommendedInstallLocation
11878                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11879                    // TODO: focus freeing disk space on the target device
11880                    final StorageManager storage = StorageManager.from(mContext);
11881                    final long lowThreshold = storage.getStorageLowBytes(
11882                            Environment.getDataDirectory());
11883
11884                    final long sizeBytes = mContainerService.calculateInstalledSize(
11885                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11886
11887                    try {
11888                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11889                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11890                                installFlags, packageAbiOverride);
11891                    } catch (InstallerException e) {
11892                        Slog.w(TAG, "Failed to free cache", e);
11893                    }
11894
11895                    /*
11896                     * The cache free must have deleted the file we
11897                     * downloaded to install.
11898                     *
11899                     * TODO: fix the "freeCache" call to not delete
11900                     *       the file we care about.
11901                     */
11902                    if (pkgLite.recommendedInstallLocation
11903                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11904                        pkgLite.recommendedInstallLocation
11905                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11906                    }
11907                }
11908            }
11909
11910            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11911                int loc = pkgLite.recommendedInstallLocation;
11912                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11913                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11914                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11915                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11916                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11917                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11918                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11919                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11920                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11921                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11922                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11923                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11924                } else {
11925                    // Override with defaults if needed.
11926                    loc = installLocationPolicy(pkgLite);
11927                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11928                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11929                    } else if (!onSd && !onInt) {
11930                        // Override install location with flags
11931                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11932                            // Set the flag to install on external media.
11933                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11934                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11935                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11936                            if (DEBUG_EPHEMERAL) {
11937                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11938                            }
11939                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11940                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11941                                    |PackageManager.INSTALL_INTERNAL);
11942                        } else {
11943                            // Make sure the flag for installing on external
11944                            // media is unset
11945                            installFlags |= PackageManager.INSTALL_INTERNAL;
11946                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11947                        }
11948                    }
11949                }
11950            }
11951
11952            final InstallArgs args = createInstallArgs(this);
11953            mArgs = args;
11954
11955            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11956                // TODO: http://b/22976637
11957                // Apps installed for "all" users use the device owner to verify the app
11958                UserHandle verifierUser = getUser();
11959                if (verifierUser == UserHandle.ALL) {
11960                    verifierUser = UserHandle.SYSTEM;
11961                }
11962
11963                /*
11964                 * Determine if we have any installed package verifiers. If we
11965                 * do, then we'll defer to them to verify the packages.
11966                 */
11967                final int requiredUid = mRequiredVerifierPackage == null ? -1
11968                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11969                                verifierUser.getIdentifier());
11970                if (!origin.existing && requiredUid != -1
11971                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11972                    final Intent verification = new Intent(
11973                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11974                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11975                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11976                            PACKAGE_MIME_TYPE);
11977                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11978
11979                    // Query all live verifiers based on current user state
11980                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
11981                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11982
11983                    if (DEBUG_VERIFY) {
11984                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11985                                + verification.toString() + " with " + pkgLite.verifiers.length
11986                                + " optional verifiers");
11987                    }
11988
11989                    final int verificationId = mPendingVerificationToken++;
11990
11991                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11992
11993                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11994                            installerPackageName);
11995
11996                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11997                            installFlags);
11998
11999                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12000                            pkgLite.packageName);
12001
12002                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12003                            pkgLite.versionCode);
12004
12005                    if (verificationInfo != null) {
12006                        if (verificationInfo.originatingUri != null) {
12007                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12008                                    verificationInfo.originatingUri);
12009                        }
12010                        if (verificationInfo.referrer != null) {
12011                            verification.putExtra(Intent.EXTRA_REFERRER,
12012                                    verificationInfo.referrer);
12013                        }
12014                        if (verificationInfo.originatingUid >= 0) {
12015                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12016                                    verificationInfo.originatingUid);
12017                        }
12018                        if (verificationInfo.installerUid >= 0) {
12019                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12020                                    verificationInfo.installerUid);
12021                        }
12022                    }
12023
12024                    final PackageVerificationState verificationState = new PackageVerificationState(
12025                            requiredUid, args);
12026
12027                    mPendingVerification.append(verificationId, verificationState);
12028
12029                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12030                            receivers, verificationState);
12031
12032                    /*
12033                     * If any sufficient verifiers were listed in the package
12034                     * manifest, attempt to ask them.
12035                     */
12036                    if (sufficientVerifiers != null) {
12037                        final int N = sufficientVerifiers.size();
12038                        if (N == 0) {
12039                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12040                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12041                        } else {
12042                            for (int i = 0; i < N; i++) {
12043                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12044
12045                                final Intent sufficientIntent = new Intent(verification);
12046                                sufficientIntent.setComponent(verifierComponent);
12047                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12048                            }
12049                        }
12050                    }
12051
12052                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12053                            mRequiredVerifierPackage, receivers);
12054                    if (ret == PackageManager.INSTALL_SUCCEEDED
12055                            && mRequiredVerifierPackage != null) {
12056                        Trace.asyncTraceBegin(
12057                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12058                        /*
12059                         * Send the intent to the required verification agent,
12060                         * but only start the verification timeout after the
12061                         * target BroadcastReceivers have run.
12062                         */
12063                        verification.setComponent(requiredVerifierComponent);
12064                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12065                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12066                                new BroadcastReceiver() {
12067                                    @Override
12068                                    public void onReceive(Context context, Intent intent) {
12069                                        final Message msg = mHandler
12070                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12071                                        msg.arg1 = verificationId;
12072                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12073                                    }
12074                                }, null, 0, null, null);
12075
12076                        /*
12077                         * We don't want the copy to proceed until verification
12078                         * succeeds, so null out this field.
12079                         */
12080                        mArgs = null;
12081                    }
12082                } else {
12083                    /*
12084                     * No package verification is enabled, so immediately start
12085                     * the remote call to initiate copy using temporary file.
12086                     */
12087                    ret = args.copyApk(mContainerService, true);
12088                }
12089            }
12090
12091            mRet = ret;
12092        }
12093
12094        @Override
12095        void handleReturnCode() {
12096            // If mArgs is null, then MCS couldn't be reached. When it
12097            // reconnects, it will try again to install. At that point, this
12098            // will succeed.
12099            if (mArgs != null) {
12100                processPendingInstall(mArgs, mRet);
12101            }
12102        }
12103
12104        @Override
12105        void handleServiceError() {
12106            mArgs = createInstallArgs(this);
12107            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12108        }
12109
12110        public boolean isForwardLocked() {
12111            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12112        }
12113    }
12114
12115    /**
12116     * Used during creation of InstallArgs
12117     *
12118     * @param installFlags package installation flags
12119     * @return true if should be installed on external storage
12120     */
12121    private static boolean installOnExternalAsec(int installFlags) {
12122        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12123            return false;
12124        }
12125        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12126            return true;
12127        }
12128        return false;
12129    }
12130
12131    /**
12132     * Used during creation of InstallArgs
12133     *
12134     * @param installFlags package installation flags
12135     * @return true if should be installed as forward locked
12136     */
12137    private static boolean installForwardLocked(int installFlags) {
12138        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12139    }
12140
12141    private InstallArgs createInstallArgs(InstallParams params) {
12142        if (params.move != null) {
12143            return new MoveInstallArgs(params);
12144        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12145            return new AsecInstallArgs(params);
12146        } else {
12147            return new FileInstallArgs(params);
12148        }
12149    }
12150
12151    /**
12152     * Create args that describe an existing installed package. Typically used
12153     * when cleaning up old installs, or used as a move source.
12154     */
12155    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12156            String resourcePath, String[] instructionSets) {
12157        final boolean isInAsec;
12158        if (installOnExternalAsec(installFlags)) {
12159            /* Apps on SD card are always in ASEC containers. */
12160            isInAsec = true;
12161        } else if (installForwardLocked(installFlags)
12162                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12163            /*
12164             * Forward-locked apps are only in ASEC containers if they're the
12165             * new style
12166             */
12167            isInAsec = true;
12168        } else {
12169            isInAsec = false;
12170        }
12171
12172        if (isInAsec) {
12173            return new AsecInstallArgs(codePath, instructionSets,
12174                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12175        } else {
12176            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12177        }
12178    }
12179
12180    static abstract class InstallArgs {
12181        /** @see InstallParams#origin */
12182        final OriginInfo origin;
12183        /** @see InstallParams#move */
12184        final MoveInfo move;
12185
12186        final IPackageInstallObserver2 observer;
12187        // Always refers to PackageManager flags only
12188        final int installFlags;
12189        final String installerPackageName;
12190        final String volumeUuid;
12191        final UserHandle user;
12192        final String abiOverride;
12193        final String[] installGrantPermissions;
12194        /** If non-null, drop an async trace when the install completes */
12195        final String traceMethod;
12196        final int traceCookie;
12197
12198        // The list of instruction sets supported by this app. This is currently
12199        // only used during the rmdex() phase to clean up resources. We can get rid of this
12200        // if we move dex files under the common app path.
12201        /* nullable */ String[] instructionSets;
12202
12203        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12204                int installFlags, String installerPackageName, String volumeUuid,
12205                UserHandle user, String[] instructionSets,
12206                String abiOverride, String[] installGrantPermissions,
12207                String traceMethod, int traceCookie) {
12208            this.origin = origin;
12209            this.move = move;
12210            this.installFlags = installFlags;
12211            this.observer = observer;
12212            this.installerPackageName = installerPackageName;
12213            this.volumeUuid = volumeUuid;
12214            this.user = user;
12215            this.instructionSets = instructionSets;
12216            this.abiOverride = abiOverride;
12217            this.installGrantPermissions = installGrantPermissions;
12218            this.traceMethod = traceMethod;
12219            this.traceCookie = traceCookie;
12220        }
12221
12222        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12223        abstract int doPreInstall(int status);
12224
12225        /**
12226         * Rename package into final resting place. All paths on the given
12227         * scanned package should be updated to reflect the rename.
12228         */
12229        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12230        abstract int doPostInstall(int status, int uid);
12231
12232        /** @see PackageSettingBase#codePathString */
12233        abstract String getCodePath();
12234        /** @see PackageSettingBase#resourcePathString */
12235        abstract String getResourcePath();
12236
12237        // Need installer lock especially for dex file removal.
12238        abstract void cleanUpResourcesLI();
12239        abstract boolean doPostDeleteLI(boolean delete);
12240
12241        /**
12242         * Called before the source arguments are copied. This is used mostly
12243         * for MoveParams when it needs to read the source file to put it in the
12244         * destination.
12245         */
12246        int doPreCopy() {
12247            return PackageManager.INSTALL_SUCCEEDED;
12248        }
12249
12250        /**
12251         * Called after the source arguments are copied. This is used mostly for
12252         * MoveParams when it needs to read the source file to put it in the
12253         * destination.
12254         *
12255         * @return
12256         */
12257        int doPostCopy(int uid) {
12258            return PackageManager.INSTALL_SUCCEEDED;
12259        }
12260
12261        protected boolean isFwdLocked() {
12262            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12263        }
12264
12265        protected boolean isExternalAsec() {
12266            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12267        }
12268
12269        protected boolean isEphemeral() {
12270            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12271        }
12272
12273        UserHandle getUser() {
12274            return user;
12275        }
12276    }
12277
12278    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12279        if (!allCodePaths.isEmpty()) {
12280            if (instructionSets == null) {
12281                throw new IllegalStateException("instructionSet == null");
12282            }
12283            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12284            for (String codePath : allCodePaths) {
12285                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12286                    try {
12287                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12288                    } catch (InstallerException ignored) {
12289                    }
12290                }
12291            }
12292        }
12293    }
12294
12295    /**
12296     * Logic to handle installation of non-ASEC applications, including copying
12297     * and renaming logic.
12298     */
12299    class FileInstallArgs extends InstallArgs {
12300        private File codeFile;
12301        private File resourceFile;
12302
12303        // Example topology:
12304        // /data/app/com.example/base.apk
12305        // /data/app/com.example/split_foo.apk
12306        // /data/app/com.example/lib/arm/libfoo.so
12307        // /data/app/com.example/lib/arm64/libfoo.so
12308        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12309
12310        /** New install */
12311        FileInstallArgs(InstallParams params) {
12312            super(params.origin, params.move, params.observer, params.installFlags,
12313                    params.installerPackageName, params.volumeUuid,
12314                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12315                    params.grantedRuntimePermissions,
12316                    params.traceMethod, params.traceCookie);
12317            if (isFwdLocked()) {
12318                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12319            }
12320        }
12321
12322        /** Existing install */
12323        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12324            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12325                    null, null, null, 0);
12326            this.codeFile = (codePath != null) ? new File(codePath) : null;
12327            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12328        }
12329
12330        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12331            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12332            try {
12333                return doCopyApk(imcs, temp);
12334            } finally {
12335                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12336            }
12337        }
12338
12339        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12340            if (origin.staged) {
12341                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12342                codeFile = origin.file;
12343                resourceFile = origin.file;
12344                return PackageManager.INSTALL_SUCCEEDED;
12345            }
12346
12347            try {
12348                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12349                final File tempDir =
12350                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12351                codeFile = tempDir;
12352                resourceFile = tempDir;
12353            } catch (IOException e) {
12354                Slog.w(TAG, "Failed to create copy file: " + e);
12355                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12356            }
12357
12358            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12359                @Override
12360                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12361                    if (!FileUtils.isValidExtFilename(name)) {
12362                        throw new IllegalArgumentException("Invalid filename: " + name);
12363                    }
12364                    try {
12365                        final File file = new File(codeFile, name);
12366                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12367                                O_RDWR | O_CREAT, 0644);
12368                        Os.chmod(file.getAbsolutePath(), 0644);
12369                        return new ParcelFileDescriptor(fd);
12370                    } catch (ErrnoException e) {
12371                        throw new RemoteException("Failed to open: " + e.getMessage());
12372                    }
12373                }
12374            };
12375
12376            int ret = PackageManager.INSTALL_SUCCEEDED;
12377            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12378            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12379                Slog.e(TAG, "Failed to copy package");
12380                return ret;
12381            }
12382
12383            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12384            NativeLibraryHelper.Handle handle = null;
12385            try {
12386                handle = NativeLibraryHelper.Handle.create(codeFile);
12387                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12388                        abiOverride);
12389            } catch (IOException e) {
12390                Slog.e(TAG, "Copying native libraries failed", e);
12391                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12392            } finally {
12393                IoUtils.closeQuietly(handle);
12394            }
12395
12396            return ret;
12397        }
12398
12399        int doPreInstall(int status) {
12400            if (status != PackageManager.INSTALL_SUCCEEDED) {
12401                cleanUp();
12402            }
12403            return status;
12404        }
12405
12406        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12407            if (status != PackageManager.INSTALL_SUCCEEDED) {
12408                cleanUp();
12409                return false;
12410            }
12411
12412            final File targetDir = codeFile.getParentFile();
12413            final File beforeCodeFile = codeFile;
12414            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12415
12416            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12417            try {
12418                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12419            } catch (ErrnoException e) {
12420                Slog.w(TAG, "Failed to rename", e);
12421                return false;
12422            }
12423
12424            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12425                Slog.w(TAG, "Failed to restorecon");
12426                return false;
12427            }
12428
12429            // Reflect the rename internally
12430            codeFile = afterCodeFile;
12431            resourceFile = afterCodeFile;
12432
12433            // Reflect the rename in scanned details
12434            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12435            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12436                    afterCodeFile, pkg.baseCodePath));
12437            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12438                    afterCodeFile, pkg.splitCodePaths));
12439
12440            // Reflect the rename in app info
12441            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12442            pkg.setApplicationInfoCodePath(pkg.codePath);
12443            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12444            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12445            pkg.setApplicationInfoResourcePath(pkg.codePath);
12446            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12447            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12448
12449            return true;
12450        }
12451
12452        int doPostInstall(int status, int uid) {
12453            if (status != PackageManager.INSTALL_SUCCEEDED) {
12454                cleanUp();
12455            }
12456            return status;
12457        }
12458
12459        @Override
12460        String getCodePath() {
12461            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12462        }
12463
12464        @Override
12465        String getResourcePath() {
12466            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12467        }
12468
12469        private boolean cleanUp() {
12470            if (codeFile == null || !codeFile.exists()) {
12471                return false;
12472            }
12473
12474            removeCodePathLI(codeFile);
12475
12476            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12477                resourceFile.delete();
12478            }
12479
12480            return true;
12481        }
12482
12483        void cleanUpResourcesLI() {
12484            // Try enumerating all code paths before deleting
12485            List<String> allCodePaths = Collections.EMPTY_LIST;
12486            if (codeFile != null && codeFile.exists()) {
12487                try {
12488                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12489                    allCodePaths = pkg.getAllCodePaths();
12490                } catch (PackageParserException e) {
12491                    // Ignored; we tried our best
12492                }
12493            }
12494
12495            cleanUp();
12496            removeDexFiles(allCodePaths, instructionSets);
12497        }
12498
12499        boolean doPostDeleteLI(boolean delete) {
12500            // XXX err, shouldn't we respect the delete flag?
12501            cleanUpResourcesLI();
12502            return true;
12503        }
12504    }
12505
12506    private boolean isAsecExternal(String cid) {
12507        final String asecPath = PackageHelper.getSdFilesystem(cid);
12508        return !asecPath.startsWith(mAsecInternalPath);
12509    }
12510
12511    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12512            PackageManagerException {
12513        if (copyRet < 0) {
12514            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12515                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12516                throw new PackageManagerException(copyRet, message);
12517            }
12518        }
12519    }
12520
12521    /**
12522     * Extract the MountService "container ID" from the full code path of an
12523     * .apk.
12524     */
12525    static String cidFromCodePath(String fullCodePath) {
12526        int eidx = fullCodePath.lastIndexOf("/");
12527        String subStr1 = fullCodePath.substring(0, eidx);
12528        int sidx = subStr1.lastIndexOf("/");
12529        return subStr1.substring(sidx+1, eidx);
12530    }
12531
12532    /**
12533     * Logic to handle installation of ASEC applications, including copying and
12534     * renaming logic.
12535     */
12536    class AsecInstallArgs extends InstallArgs {
12537        static final String RES_FILE_NAME = "pkg.apk";
12538        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12539
12540        String cid;
12541        String packagePath;
12542        String resourcePath;
12543
12544        /** New install */
12545        AsecInstallArgs(InstallParams params) {
12546            super(params.origin, params.move, params.observer, params.installFlags,
12547                    params.installerPackageName, params.volumeUuid,
12548                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12549                    params.grantedRuntimePermissions,
12550                    params.traceMethod, params.traceCookie);
12551        }
12552
12553        /** Existing install */
12554        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12555                        boolean isExternal, boolean isForwardLocked) {
12556            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12557                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12558                    instructionSets, null, null, null, 0);
12559            // Hackily pretend we're still looking at a full code path
12560            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12561                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12562            }
12563
12564            // Extract cid from fullCodePath
12565            int eidx = fullCodePath.lastIndexOf("/");
12566            String subStr1 = fullCodePath.substring(0, eidx);
12567            int sidx = subStr1.lastIndexOf("/");
12568            cid = subStr1.substring(sidx+1, eidx);
12569            setMountPath(subStr1);
12570        }
12571
12572        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12573            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12574                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12575                    instructionSets, null, null, null, 0);
12576            this.cid = cid;
12577            setMountPath(PackageHelper.getSdDir(cid));
12578        }
12579
12580        void createCopyFile() {
12581            cid = mInstallerService.allocateExternalStageCidLegacy();
12582        }
12583
12584        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12585            if (origin.staged && origin.cid != null) {
12586                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12587                cid = origin.cid;
12588                setMountPath(PackageHelper.getSdDir(cid));
12589                return PackageManager.INSTALL_SUCCEEDED;
12590            }
12591
12592            if (temp) {
12593                createCopyFile();
12594            } else {
12595                /*
12596                 * Pre-emptively destroy the container since it's destroyed if
12597                 * copying fails due to it existing anyway.
12598                 */
12599                PackageHelper.destroySdDir(cid);
12600            }
12601
12602            final String newMountPath = imcs.copyPackageToContainer(
12603                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12604                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12605
12606            if (newMountPath != null) {
12607                setMountPath(newMountPath);
12608                return PackageManager.INSTALL_SUCCEEDED;
12609            } else {
12610                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12611            }
12612        }
12613
12614        @Override
12615        String getCodePath() {
12616            return packagePath;
12617        }
12618
12619        @Override
12620        String getResourcePath() {
12621            return resourcePath;
12622        }
12623
12624        int doPreInstall(int status) {
12625            if (status != PackageManager.INSTALL_SUCCEEDED) {
12626                // Destroy container
12627                PackageHelper.destroySdDir(cid);
12628            } else {
12629                boolean mounted = PackageHelper.isContainerMounted(cid);
12630                if (!mounted) {
12631                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12632                            Process.SYSTEM_UID);
12633                    if (newMountPath != null) {
12634                        setMountPath(newMountPath);
12635                    } else {
12636                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12637                    }
12638                }
12639            }
12640            return status;
12641        }
12642
12643        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12644            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12645            String newMountPath = null;
12646            if (PackageHelper.isContainerMounted(cid)) {
12647                // Unmount the container
12648                if (!PackageHelper.unMountSdDir(cid)) {
12649                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12650                    return false;
12651                }
12652            }
12653            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12654                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12655                        " which might be stale. Will try to clean up.");
12656                // Clean up the stale container and proceed to recreate.
12657                if (!PackageHelper.destroySdDir(newCacheId)) {
12658                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12659                    return false;
12660                }
12661                // Successfully cleaned up stale container. Try to rename again.
12662                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12663                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12664                            + " inspite of cleaning it up.");
12665                    return false;
12666                }
12667            }
12668            if (!PackageHelper.isContainerMounted(newCacheId)) {
12669                Slog.w(TAG, "Mounting container " + newCacheId);
12670                newMountPath = PackageHelper.mountSdDir(newCacheId,
12671                        getEncryptKey(), Process.SYSTEM_UID);
12672            } else {
12673                newMountPath = PackageHelper.getSdDir(newCacheId);
12674            }
12675            if (newMountPath == null) {
12676                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12677                return false;
12678            }
12679            Log.i(TAG, "Succesfully renamed " + cid +
12680                    " to " + newCacheId +
12681                    " at new path: " + newMountPath);
12682            cid = newCacheId;
12683
12684            final File beforeCodeFile = new File(packagePath);
12685            setMountPath(newMountPath);
12686            final File afterCodeFile = new File(packagePath);
12687
12688            // Reflect the rename in scanned details
12689            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12690            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12691                    afterCodeFile, pkg.baseCodePath));
12692            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12693                    afterCodeFile, pkg.splitCodePaths));
12694
12695            // Reflect the rename in app info
12696            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12697            pkg.setApplicationInfoCodePath(pkg.codePath);
12698            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12699            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12700            pkg.setApplicationInfoResourcePath(pkg.codePath);
12701            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12702            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12703
12704            return true;
12705        }
12706
12707        private void setMountPath(String mountPath) {
12708            final File mountFile = new File(mountPath);
12709
12710            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12711            if (monolithicFile.exists()) {
12712                packagePath = monolithicFile.getAbsolutePath();
12713                if (isFwdLocked()) {
12714                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12715                } else {
12716                    resourcePath = packagePath;
12717                }
12718            } else {
12719                packagePath = mountFile.getAbsolutePath();
12720                resourcePath = packagePath;
12721            }
12722        }
12723
12724        int doPostInstall(int status, int uid) {
12725            if (status != PackageManager.INSTALL_SUCCEEDED) {
12726                cleanUp();
12727            } else {
12728                final int groupOwner;
12729                final String protectedFile;
12730                if (isFwdLocked()) {
12731                    groupOwner = UserHandle.getSharedAppGid(uid);
12732                    protectedFile = RES_FILE_NAME;
12733                } else {
12734                    groupOwner = -1;
12735                    protectedFile = null;
12736                }
12737
12738                if (uid < Process.FIRST_APPLICATION_UID
12739                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12740                    Slog.e(TAG, "Failed to finalize " + cid);
12741                    PackageHelper.destroySdDir(cid);
12742                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12743                }
12744
12745                boolean mounted = PackageHelper.isContainerMounted(cid);
12746                if (!mounted) {
12747                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12748                }
12749            }
12750            return status;
12751        }
12752
12753        private void cleanUp() {
12754            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12755
12756            // Destroy secure container
12757            PackageHelper.destroySdDir(cid);
12758        }
12759
12760        private List<String> getAllCodePaths() {
12761            final File codeFile = new File(getCodePath());
12762            if (codeFile != null && codeFile.exists()) {
12763                try {
12764                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12765                    return pkg.getAllCodePaths();
12766                } catch (PackageParserException e) {
12767                    // Ignored; we tried our best
12768                }
12769            }
12770            return Collections.EMPTY_LIST;
12771        }
12772
12773        void cleanUpResourcesLI() {
12774            // Enumerate all code paths before deleting
12775            cleanUpResourcesLI(getAllCodePaths());
12776        }
12777
12778        private void cleanUpResourcesLI(List<String> allCodePaths) {
12779            cleanUp();
12780            removeDexFiles(allCodePaths, instructionSets);
12781        }
12782
12783        String getPackageName() {
12784            return getAsecPackageName(cid);
12785        }
12786
12787        boolean doPostDeleteLI(boolean delete) {
12788            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12789            final List<String> allCodePaths = getAllCodePaths();
12790            boolean mounted = PackageHelper.isContainerMounted(cid);
12791            if (mounted) {
12792                // Unmount first
12793                if (PackageHelper.unMountSdDir(cid)) {
12794                    mounted = false;
12795                }
12796            }
12797            if (!mounted && delete) {
12798                cleanUpResourcesLI(allCodePaths);
12799            }
12800            return !mounted;
12801        }
12802
12803        @Override
12804        int doPreCopy() {
12805            if (isFwdLocked()) {
12806                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12807                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12808                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12809                }
12810            }
12811
12812            return PackageManager.INSTALL_SUCCEEDED;
12813        }
12814
12815        @Override
12816        int doPostCopy(int uid) {
12817            if (isFwdLocked()) {
12818                if (uid < Process.FIRST_APPLICATION_UID
12819                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12820                                RES_FILE_NAME)) {
12821                    Slog.e(TAG, "Failed to finalize " + cid);
12822                    PackageHelper.destroySdDir(cid);
12823                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12824                }
12825            }
12826
12827            return PackageManager.INSTALL_SUCCEEDED;
12828        }
12829    }
12830
12831    /**
12832     * Logic to handle movement of existing installed applications.
12833     */
12834    class MoveInstallArgs extends InstallArgs {
12835        private File codeFile;
12836        private File resourceFile;
12837
12838        /** New install */
12839        MoveInstallArgs(InstallParams params) {
12840            super(params.origin, params.move, params.observer, params.installFlags,
12841                    params.installerPackageName, params.volumeUuid,
12842                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12843                    params.grantedRuntimePermissions,
12844                    params.traceMethod, params.traceCookie);
12845        }
12846
12847        int copyApk(IMediaContainerService imcs, boolean temp) {
12848            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12849                    + move.fromUuid + " to " + move.toUuid);
12850            synchronized (mInstaller) {
12851                try {
12852                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12853                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12854                } catch (InstallerException e) {
12855                    Slog.w(TAG, "Failed to move app", e);
12856                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12857                }
12858            }
12859
12860            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12861            resourceFile = codeFile;
12862            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12863
12864            return PackageManager.INSTALL_SUCCEEDED;
12865        }
12866
12867        int doPreInstall(int status) {
12868            if (status != PackageManager.INSTALL_SUCCEEDED) {
12869                cleanUp(move.toUuid);
12870            }
12871            return status;
12872        }
12873
12874        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12875            if (status != PackageManager.INSTALL_SUCCEEDED) {
12876                cleanUp(move.toUuid);
12877                return false;
12878            }
12879
12880            // Reflect the move in app info
12881            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12882            pkg.setApplicationInfoCodePath(pkg.codePath);
12883            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12884            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12885            pkg.setApplicationInfoResourcePath(pkg.codePath);
12886            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12887            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12888
12889            return true;
12890        }
12891
12892        int doPostInstall(int status, int uid) {
12893            if (status == PackageManager.INSTALL_SUCCEEDED) {
12894                cleanUp(move.fromUuid);
12895            } else {
12896                cleanUp(move.toUuid);
12897            }
12898            return status;
12899        }
12900
12901        @Override
12902        String getCodePath() {
12903            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12904        }
12905
12906        @Override
12907        String getResourcePath() {
12908            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12909        }
12910
12911        private boolean cleanUp(String volumeUuid) {
12912            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12913                    move.dataAppName);
12914            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12915            synchronized (mInstallLock) {
12916                // Clean up both app data and code
12917                removeDataDirsLI(volumeUuid, move.packageName);
12918                removeCodePathLI(codeFile);
12919            }
12920            return true;
12921        }
12922
12923        void cleanUpResourcesLI() {
12924            throw new UnsupportedOperationException();
12925        }
12926
12927        boolean doPostDeleteLI(boolean delete) {
12928            throw new UnsupportedOperationException();
12929        }
12930    }
12931
12932    static String getAsecPackageName(String packageCid) {
12933        int idx = packageCid.lastIndexOf("-");
12934        if (idx == -1) {
12935            return packageCid;
12936        }
12937        return packageCid.substring(0, idx);
12938    }
12939
12940    // Utility method used to create code paths based on package name and available index.
12941    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12942        String idxStr = "";
12943        int idx = 1;
12944        // Fall back to default value of idx=1 if prefix is not
12945        // part of oldCodePath
12946        if (oldCodePath != null) {
12947            String subStr = oldCodePath;
12948            // Drop the suffix right away
12949            if (suffix != null && subStr.endsWith(suffix)) {
12950                subStr = subStr.substring(0, subStr.length() - suffix.length());
12951            }
12952            // If oldCodePath already contains prefix find out the
12953            // ending index to either increment or decrement.
12954            int sidx = subStr.lastIndexOf(prefix);
12955            if (sidx != -1) {
12956                subStr = subStr.substring(sidx + prefix.length());
12957                if (subStr != null) {
12958                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12959                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12960                    }
12961                    try {
12962                        idx = Integer.parseInt(subStr);
12963                        if (idx <= 1) {
12964                            idx++;
12965                        } else {
12966                            idx--;
12967                        }
12968                    } catch(NumberFormatException e) {
12969                    }
12970                }
12971            }
12972        }
12973        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12974        return prefix + idxStr;
12975    }
12976
12977    private File getNextCodePath(File targetDir, String packageName) {
12978        int suffix = 1;
12979        File result;
12980        do {
12981            result = new File(targetDir, packageName + "-" + suffix);
12982            suffix++;
12983        } while (result.exists());
12984        return result;
12985    }
12986
12987    // Utility method that returns the relative package path with respect
12988    // to the installation directory. Like say for /data/data/com.test-1.apk
12989    // string com.test-1 is returned.
12990    static String deriveCodePathName(String codePath) {
12991        if (codePath == null) {
12992            return null;
12993        }
12994        final File codeFile = new File(codePath);
12995        final String name = codeFile.getName();
12996        if (codeFile.isDirectory()) {
12997            return name;
12998        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12999            final int lastDot = name.lastIndexOf('.');
13000            return name.substring(0, lastDot);
13001        } else {
13002            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13003            return null;
13004        }
13005    }
13006
13007    static class PackageInstalledInfo {
13008        String name;
13009        int uid;
13010        // The set of users that originally had this package installed.
13011        int[] origUsers;
13012        // The set of users that now have this package installed.
13013        int[] newUsers;
13014        PackageParser.Package pkg;
13015        int returnCode;
13016        String returnMsg;
13017        PackageRemovedInfo removedInfo;
13018        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13019
13020        public void setError(int code, String msg) {
13021            setReturnCode(code);
13022            setReturnMessage(msg);
13023            Slog.w(TAG, msg);
13024        }
13025
13026        public void setError(String msg, PackageParserException e) {
13027            setReturnCode(e.error);
13028            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13029            Slog.w(TAG, msg, e);
13030        }
13031
13032        public void setError(String msg, PackageManagerException e) {
13033            returnCode = e.error;
13034            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13035            Slog.w(TAG, msg, e);
13036        }
13037
13038        public void setReturnCode(int returnCode) {
13039            this.returnCode = returnCode;
13040            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13041            for (int i = 0; i < childCount; i++) {
13042                addedChildPackages.valueAt(i).returnCode = returnCode;
13043            }
13044        }
13045
13046        private void setReturnMessage(String returnMsg) {
13047            this.returnMsg = returnMsg;
13048            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13049            for (int i = 0; i < childCount; i++) {
13050                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13051            }
13052        }
13053
13054        // In some error cases we want to convey more info back to the observer
13055        String origPackage;
13056        String origPermission;
13057    }
13058
13059    /*
13060     * Install a non-existing package.
13061     */
13062    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13063            UserHandle user, String installerPackageName, String volumeUuid,
13064            PackageInstalledInfo res) {
13065        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13066
13067        // Remember this for later, in case we need to rollback this install
13068        String pkgName = pkg.packageName;
13069
13070        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13071
13072        synchronized(mPackages) {
13073            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13074                // A package with the same name is already installed, though
13075                // it has been renamed to an older name.  The package we
13076                // are trying to install should be installed as an update to
13077                // the existing one, but that has not been requested, so bail.
13078                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13079                        + " without first uninstalling package running as "
13080                        + mSettings.mRenamedPackages.get(pkgName));
13081                return;
13082            }
13083            if (mPackages.containsKey(pkgName)) {
13084                // Don't allow installation over an existing package with the same name.
13085                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13086                        + " without first uninstalling.");
13087                return;
13088            }
13089        }
13090
13091        try {
13092            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13093                    System.currentTimeMillis(), user);
13094
13095            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13096
13097            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13098                prepareAppDataAfterInstall(newPackage);
13099
13100            } else {
13101                // Remove package from internal structures, but keep around any
13102                // data that might have already existed
13103                deletePackageLI(pkgName, UserHandle.ALL, false, null,
13104                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13105            }
13106        } catch (PackageManagerException e) {
13107            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13108        }
13109
13110        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13111    }
13112
13113    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13114        // Can't rotate keys during boot or if sharedUser.
13115        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13116                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13117            return false;
13118        }
13119        // app is using upgradeKeySets; make sure all are valid
13120        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13121        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13122        for (int i = 0; i < upgradeKeySets.length; i++) {
13123            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13124                Slog.wtf(TAG, "Package "
13125                         + (oldPs.name != null ? oldPs.name : "<null>")
13126                         + " contains upgrade-key-set reference to unknown key-set: "
13127                         + upgradeKeySets[i]
13128                         + " reverting to signatures check.");
13129                return false;
13130            }
13131        }
13132        return true;
13133    }
13134
13135    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13136        // Upgrade keysets are being used.  Determine if new package has a superset of the
13137        // required keys.
13138        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13139        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13140        for (int i = 0; i < upgradeKeySets.length; i++) {
13141            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13142            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13143                return true;
13144            }
13145        }
13146        return false;
13147    }
13148
13149    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13150            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13151        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13152
13153        final PackageParser.Package oldPackage;
13154        final String pkgName = pkg.packageName;
13155        final int[] allUsers;
13156        final boolean weFroze;
13157
13158        // First find the old package info and check signatures
13159        synchronized(mPackages) {
13160            oldPackage = mPackages.get(pkgName);
13161            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13162            if (isEphemeral && !oldIsEphemeral) {
13163                // can't downgrade from full to ephemeral
13164                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13165                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13166                return;
13167            }
13168            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13169            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13170            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13171                if (!checkUpgradeKeySetLP(ps, pkg)) {
13172                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13173                            "New package not signed by keys specified by upgrade-keysets: "
13174                                    + pkgName);
13175                    return;
13176                }
13177            } else {
13178                // default to original signature matching
13179                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13180                        != PackageManager.SIGNATURE_MATCH) {
13181                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13182                            "New package has a different signature: " + pkgName);
13183                    return;
13184                }
13185            }
13186
13187            // In case of rollback, remember per-user/profile install state
13188            allUsers = sUserManager.getUserIds();
13189
13190            // Mark the app as frozen to prevent launching during the upgrade
13191            // process, and then kill all running instances
13192            if (!ps.frozen) {
13193                ps.frozen = true;
13194                weFroze = true;
13195            } else {
13196                weFroze = false;
13197            }
13198        }
13199
13200        try {
13201            replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers,
13202                    installerPackageName, res);
13203        } finally {
13204            // Regardless of success or failure of upgrade steps above, always
13205            // unfreeze the package if we froze it
13206            if (weFroze) {
13207                unfreezePackage(pkgName);
13208            }
13209        }
13210    }
13211
13212    private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage,
13213            int parseFlags, int scanFlags, UserHandle user, int[] allUsers,
13214            String installerPackageName, PackageInstalledInfo res) {
13215        // Update what is removed
13216        res.removedInfo = new PackageRemovedInfo();
13217        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13218        res.removedInfo.removedPackage = oldPackage.packageName;
13219        res.removedInfo.isUpdate = true;
13220        final int childCount = (oldPackage.childPackages != null)
13221                ? oldPackage.childPackages.size() : 0;
13222        for (int i = 0; i < childCount; i++) {
13223            boolean childPackageUpdated = false;
13224            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13225            if (res.addedChildPackages != null) {
13226                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13227                if (childRes != null) {
13228                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13229                    childRes.removedInfo.removedPackage = childPkg.packageName;
13230                    childRes.removedInfo.isUpdate = true;
13231                    childPackageUpdated = true;
13232                }
13233            }
13234            if (!childPackageUpdated) {
13235                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13236                childRemovedRes.removedPackage = childPkg.packageName;
13237                childRemovedRes.isUpdate = false;
13238                childRemovedRes.dataRemoved = true;
13239                synchronized (mPackages) {
13240                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13241                    if (childPs != null) {
13242                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13243                    }
13244                }
13245                if (res.removedInfo.removedChildPackages == null) {
13246                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13247                }
13248                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13249            }
13250        }
13251
13252        boolean sysPkg = (isSystemApp(oldPackage));
13253        if (sysPkg) {
13254            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13255                    user, allUsers, installerPackageName, res);
13256        } else {
13257            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13258                    user, allUsers, installerPackageName, res);
13259        }
13260    }
13261
13262    public List<String> getPreviousCodePaths(String packageName) {
13263        final PackageSetting ps = mSettings.mPackages.get(packageName);
13264        final List<String> result = new ArrayList<String>();
13265        if (ps != null && ps.oldCodePaths != null) {
13266            result.addAll(ps.oldCodePaths);
13267        }
13268        return result;
13269    }
13270
13271    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13272            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13273            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13274        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13275                + deletedPackage);
13276
13277        String pkgName = deletedPackage.packageName;
13278        boolean deletedPkg = true;
13279        boolean addedPkg = false;
13280        boolean updatedSettings = false;
13281        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13282        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13283                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13284
13285        final long origUpdateTime = (pkg.mExtras != null)
13286                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13287
13288        // First delete the existing package while retaining the data directory
13289        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13290                res.removedInfo, true, pkg)) {
13291            // If the existing package wasn't successfully deleted
13292            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13293            deletedPkg = false;
13294        } else {
13295            // Successfully deleted the old package; proceed with replace.
13296
13297            // If deleted package lived in a container, give users a chance to
13298            // relinquish resources before killing.
13299            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13300                if (DEBUG_INSTALL) {
13301                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13302                }
13303                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13304                final ArrayList<String> pkgList = new ArrayList<String>(1);
13305                pkgList.add(deletedPackage.applicationInfo.packageName);
13306                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13307            }
13308
13309            deleteCodeCacheDirsLI(pkg);
13310            deleteProfilesLI(pkg, /*destroy*/ false);
13311
13312            try {
13313                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13314                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13315                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13316
13317                // Update the in-memory copy of the previous code paths.
13318                PackageSetting ps = mSettings.mPackages.get(pkgName);
13319                if (!killApp) {
13320                    if (ps.oldCodePaths == null) {
13321                        ps.oldCodePaths = new ArraySet<>();
13322                    }
13323                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13324                    if (deletedPackage.splitCodePaths != null) {
13325                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13326                    }
13327                } else {
13328                    ps.oldCodePaths = null;
13329                }
13330                if (ps.childPackageNames != null) {
13331                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13332                        final String childPkgName = ps.childPackageNames.get(i);
13333                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13334                        childPs.oldCodePaths = ps.oldCodePaths;
13335                    }
13336                }
13337                prepareAppDataAfterInstall(newPackage);
13338                addedPkg = true;
13339            } catch (PackageManagerException e) {
13340                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13341            }
13342        }
13343
13344        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13345            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13346
13347            // Revert all internal state mutations and added folders for the failed install
13348            if (addedPkg) {
13349                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13350                        res.removedInfo, true, null);
13351            }
13352
13353            // Restore the old package
13354            if (deletedPkg) {
13355                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13356                File restoreFile = new File(deletedPackage.codePath);
13357                // Parse old package
13358                boolean oldExternal = isExternal(deletedPackage);
13359                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13360                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13361                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13362                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13363                try {
13364                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13365                            null);
13366                } catch (PackageManagerException e) {
13367                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13368                            + e.getMessage());
13369                    return;
13370                }
13371
13372                synchronized (mPackages) {
13373                    // Ensure the installer package name up to date
13374                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13375
13376                    // Update permissions for restored package
13377                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13378
13379                    mSettings.writeLPr();
13380                }
13381
13382                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13383            }
13384        } else {
13385            synchronized (mPackages) {
13386                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13387                if (ps != null) {
13388                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13389                    if (res.removedInfo.removedChildPackages != null) {
13390                        final int childCount = res.removedInfo.removedChildPackages.size();
13391                        // Iterate in reverse as we may modify the collection
13392                        for (int i = childCount - 1; i >= 0; i--) {
13393                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13394                            if (res.addedChildPackages.containsKey(childPackageName)) {
13395                                res.removedInfo.removedChildPackages.removeAt(i);
13396                            } else {
13397                                PackageRemovedInfo childInfo = res.removedInfo
13398                                        .removedChildPackages.valueAt(i);
13399                                childInfo.removedForAllUsers = mPackages.get(
13400                                        childInfo.removedPackage) == null;
13401                            }
13402                        }
13403                    }
13404                }
13405            }
13406        }
13407    }
13408
13409    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13410            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13411            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13412        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13413                + ", old=" + deletedPackage);
13414
13415        final boolean disabledSystem;
13416
13417        // Set the system/privileged flags as needed
13418        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13419        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13420                != 0) {
13421            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13422        }
13423
13424        // Kill package processes including services, providers, etc.
13425        killPackage(deletedPackage, "replace sys pkg");
13426
13427        // Remove existing system package
13428        removePackageLI(deletedPackage, true);
13429
13430        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13431        if (!disabledSystem) {
13432            // We didn't need to disable the .apk as a current system package,
13433            // which means we are replacing another update that is already
13434            // installed.  We need to make sure to delete the older one's .apk.
13435            res.removedInfo.args = createInstallArgsForExisting(0,
13436                    deletedPackage.applicationInfo.getCodePath(),
13437                    deletedPackage.applicationInfo.getResourcePath(),
13438                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13439        } else {
13440            res.removedInfo.args = null;
13441        }
13442
13443        // Successfully disabled the old package. Now proceed with re-installation
13444        deleteCodeCacheDirsLI(pkg);
13445        deleteProfilesLI(pkg, /*destroy*/ false);
13446
13447        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13448        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13449                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13450
13451        PackageParser.Package newPackage = null;
13452        try {
13453            // Add the package to the internal data structures
13454            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13455
13456            // Set the update and install times
13457            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13458            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13459                    System.currentTimeMillis());
13460
13461            // Check for shared user id changes
13462            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13463                    deletedPackage, newPackage);
13464            if (invalidPackageName != null) {
13465                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13466                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13467                                + " to " + invalidPackageName);
13468            }
13469
13470            // Update the package dynamic state if succeeded
13471            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13472                // Now that the install succeeded make sure we remove data
13473                // directories for any child package the update removed.
13474                final int deletedChildCount = (deletedPackage.childPackages != null)
13475                        ? deletedPackage.childPackages.size() : 0;
13476                final int newChildCount = (newPackage.childPackages != null)
13477                        ? newPackage.childPackages.size() : 0;
13478                for (int i = 0; i < deletedChildCount; i++) {
13479                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13480                    boolean childPackageDeleted = true;
13481                    for (int j = 0; j < newChildCount; j++) {
13482                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13483                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13484                            childPackageDeleted = false;
13485                            break;
13486                        }
13487                    }
13488                    if (childPackageDeleted) {
13489                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13490                                deletedChildPkg.packageName);
13491                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13492                            PackageRemovedInfo removedChildRes = res.removedInfo
13493                                    .removedChildPackages.get(deletedChildPkg.packageName);
13494                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13495                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13496                        }
13497                    }
13498                }
13499
13500                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13501                prepareAppDataAfterInstall(newPackage);
13502            }
13503        } catch (PackageManagerException e) {
13504            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13505            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13506        }
13507
13508        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13509            // Re installation failed. Restore old information
13510            // Remove new pkg information
13511            if (newPackage != null) {
13512                removeInstalledPackageLI(newPackage, true);
13513            }
13514            // Add back the old system package
13515            try {
13516                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13517            } catch (PackageManagerException e) {
13518                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13519            }
13520
13521            synchronized (mPackages) {
13522                if (disabledSystem) {
13523                    enableSystemPackageLPw(deletedPackage);
13524                }
13525
13526                // Ensure the installer package name up to date
13527                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13528
13529                // Update permissions for restored package
13530                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13531
13532                mSettings.writeLPr();
13533            }
13534
13535            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13536                    + " after failed upgrade");
13537        }
13538    }
13539
13540    /**
13541     * Checks whether the parent or any of the child packages have a change shared
13542     * user. For a package to be a valid update the shred users of the parent and
13543     * the children should match. We may later support changing child shared users.
13544     * @param oldPkg The updated package.
13545     * @param newPkg The update package.
13546     * @return The shared user that change between the versions.
13547     */
13548    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13549            PackageParser.Package newPkg) {
13550        // Check parent shared user
13551        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13552            return newPkg.packageName;
13553        }
13554        // Check child shared users
13555        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13556        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13557        for (int i = 0; i < newChildCount; i++) {
13558            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13559            // If this child was present, did it have the same shared user?
13560            for (int j = 0; j < oldChildCount; j++) {
13561                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13562                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13563                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13564                    return newChildPkg.packageName;
13565                }
13566            }
13567        }
13568        return null;
13569    }
13570
13571    private void removeNativeBinariesLI(PackageSetting ps) {
13572        // Remove the lib path for the parent package
13573        if (ps != null) {
13574            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13575            // Remove the lib path for the child packages
13576            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13577            for (int i = 0; i < childCount; i++) {
13578                PackageSetting childPs = null;
13579                synchronized (mPackages) {
13580                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13581                }
13582                if (childPs != null) {
13583                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13584                            .legacyNativeLibraryPathString);
13585                }
13586            }
13587        }
13588    }
13589
13590    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13591        // Enable the parent package
13592        mSettings.enableSystemPackageLPw(pkg.packageName);
13593        // Enable the child packages
13594        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13595        for (int i = 0; i < childCount; i++) {
13596            PackageParser.Package childPkg = pkg.childPackages.get(i);
13597            mSettings.enableSystemPackageLPw(childPkg.packageName);
13598        }
13599    }
13600
13601    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13602            PackageParser.Package newPkg) {
13603        // Disable the parent package (parent always replaced)
13604        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13605        // Disable the child packages
13606        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13607        for (int i = 0; i < childCount; i++) {
13608            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13609            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13610            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13611        }
13612        return disabled;
13613    }
13614
13615    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13616            String installerPackageName) {
13617        // Enable the parent package
13618        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13619        // Enable the child packages
13620        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13621        for (int i = 0; i < childCount; i++) {
13622            PackageParser.Package childPkg = pkg.childPackages.get(i);
13623            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13624        }
13625    }
13626
13627    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13628        // Collect all used permissions in the UID
13629        ArraySet<String> usedPermissions = new ArraySet<>();
13630        final int packageCount = su.packages.size();
13631        for (int i = 0; i < packageCount; i++) {
13632            PackageSetting ps = su.packages.valueAt(i);
13633            if (ps.pkg == null) {
13634                continue;
13635            }
13636            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13637            for (int j = 0; j < requestedPermCount; j++) {
13638                String permission = ps.pkg.requestedPermissions.get(j);
13639                BasePermission bp = mSettings.mPermissions.get(permission);
13640                if (bp != null) {
13641                    usedPermissions.add(permission);
13642                }
13643            }
13644        }
13645
13646        PermissionsState permissionsState = su.getPermissionsState();
13647        // Prune install permissions
13648        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13649        final int installPermCount = installPermStates.size();
13650        for (int i = installPermCount - 1; i >= 0;  i--) {
13651            PermissionState permissionState = installPermStates.get(i);
13652            if (!usedPermissions.contains(permissionState.getName())) {
13653                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13654                if (bp != null) {
13655                    permissionsState.revokeInstallPermission(bp);
13656                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13657                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13658                }
13659            }
13660        }
13661
13662        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13663
13664        // Prune runtime permissions
13665        for (int userId : allUserIds) {
13666            List<PermissionState> runtimePermStates = permissionsState
13667                    .getRuntimePermissionStates(userId);
13668            final int runtimePermCount = runtimePermStates.size();
13669            for (int i = runtimePermCount - 1; i >= 0; i--) {
13670                PermissionState permissionState = runtimePermStates.get(i);
13671                if (!usedPermissions.contains(permissionState.getName())) {
13672                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13673                    if (bp != null) {
13674                        permissionsState.revokeRuntimePermission(bp, userId);
13675                        permissionsState.updatePermissionFlags(bp, userId,
13676                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13677                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13678                                runtimePermissionChangedUserIds, userId);
13679                    }
13680                }
13681            }
13682        }
13683
13684        return runtimePermissionChangedUserIds;
13685    }
13686
13687    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13688            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13689        // Update the parent package setting
13690        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13691                res, user);
13692        // Update the child packages setting
13693        final int childCount = (newPackage.childPackages != null)
13694                ? newPackage.childPackages.size() : 0;
13695        for (int i = 0; i < childCount; i++) {
13696            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13697            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13698            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13699                    childRes.origUsers, childRes, user);
13700        }
13701    }
13702
13703    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13704            String installerPackageName, int[] allUsers, int[] installedForUsers,
13705            PackageInstalledInfo res, UserHandle user) {
13706        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13707
13708        String pkgName = newPackage.packageName;
13709        synchronized (mPackages) {
13710            //write settings. the installStatus will be incomplete at this stage.
13711            //note that the new package setting would have already been
13712            //added to mPackages. It hasn't been persisted yet.
13713            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13714            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13715            mSettings.writeLPr();
13716            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13717        }
13718
13719        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13720        synchronized (mPackages) {
13721            updatePermissionsLPw(newPackage.packageName, newPackage,
13722                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13723                            ? UPDATE_PERMISSIONS_ALL : 0));
13724            // For system-bundled packages, we assume that installing an upgraded version
13725            // of the package implies that the user actually wants to run that new code,
13726            // so we enable the package.
13727            PackageSetting ps = mSettings.mPackages.get(pkgName);
13728            final int userId = user.getIdentifier();
13729            if (ps != null) {
13730                if (isSystemApp(newPackage)) {
13731                    if (DEBUG_INSTALL) {
13732                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13733                    }
13734                    // Enable system package for requested users
13735                    if (res.origUsers != null) {
13736                        for (int origUserId : res.origUsers) {
13737                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13738                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13739                                        origUserId, installerPackageName);
13740                            }
13741                        }
13742                    }
13743                    // Also convey the prior install/uninstall state
13744                    if (allUsers != null && installedForUsers != null) {
13745                        for (int currentUserId : allUsers) {
13746                            final boolean installed = ArrayUtils.contains(
13747                                    installedForUsers, currentUserId);
13748                            if (DEBUG_INSTALL) {
13749                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13750                            }
13751                            ps.setInstalled(installed, currentUserId);
13752                        }
13753                        // these install state changes will be persisted in the
13754                        // upcoming call to mSettings.writeLPr().
13755                    }
13756                }
13757                // It's implied that when a user requests installation, they want the app to be
13758                // installed and enabled.
13759                if (userId != UserHandle.USER_ALL) {
13760                    ps.setInstalled(true, userId);
13761                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13762                }
13763            }
13764            res.name = pkgName;
13765            res.uid = newPackage.applicationInfo.uid;
13766            res.pkg = newPackage;
13767            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13768            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13769            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13770            //to update install status
13771            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13772            mSettings.writeLPr();
13773            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13774        }
13775
13776        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13777    }
13778
13779    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13780        try {
13781            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13782            installPackageLI(args, res);
13783        } finally {
13784            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13785        }
13786    }
13787
13788    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13789        final int installFlags = args.installFlags;
13790        final String installerPackageName = args.installerPackageName;
13791        final String volumeUuid = args.volumeUuid;
13792        final File tmpPackageFile = new File(args.getCodePath());
13793        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13794        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13795                || (args.volumeUuid != null));
13796        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13797        boolean replace = false;
13798        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13799        if (args.move != null) {
13800            // moving a complete application; perform an initial scan on the new install location
13801            scanFlags |= SCAN_INITIAL;
13802        }
13803        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
13804            scanFlags |= SCAN_DONT_KILL_APP;
13805        }
13806
13807        // Result object to be returned
13808        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13809
13810        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13811
13812        // Sanity check
13813        if (ephemeral && (forwardLocked || onExternal)) {
13814            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13815                    + " external=" + onExternal);
13816            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13817            return;
13818        }
13819
13820        // Retrieve PackageSettings and parse package
13821        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13822                | PackageParser.PARSE_ENFORCE_CODE
13823                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13824                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13825                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13826        PackageParser pp = new PackageParser();
13827        pp.setSeparateProcesses(mSeparateProcesses);
13828        pp.setDisplayMetrics(mMetrics);
13829
13830        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13831        final PackageParser.Package pkg;
13832        try {
13833            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13834        } catch (PackageParserException e) {
13835            res.setError("Failed parse during installPackageLI", e);
13836            return;
13837        } finally {
13838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13839        }
13840
13841        // If we are installing a clustered package add results for the children
13842        if (pkg.childPackages != null) {
13843            synchronized (mPackages) {
13844                final int childCount = pkg.childPackages.size();
13845                for (int i = 0; i < childCount; i++) {
13846                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13847                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13848                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13849                    childRes.pkg = childPkg;
13850                    childRes.name = childPkg.packageName;
13851                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13852                    if (childPs != null) {
13853                        childRes.origUsers = childPs.queryInstalledUsers(
13854                                sUserManager.getUserIds(), true);
13855                    }
13856                    if ((mPackages.containsKey(childPkg.packageName))) {
13857                        childRes.removedInfo = new PackageRemovedInfo();
13858                        childRes.removedInfo.removedPackage = childPkg.packageName;
13859                    }
13860                    if (res.addedChildPackages == null) {
13861                        res.addedChildPackages = new ArrayMap<>();
13862                    }
13863                    res.addedChildPackages.put(childPkg.packageName, childRes);
13864                }
13865            }
13866        }
13867
13868        // If package doesn't declare API override, mark that we have an install
13869        // time CPU ABI override.
13870        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13871            pkg.cpuAbiOverride = args.abiOverride;
13872        }
13873
13874        String pkgName = res.name = pkg.packageName;
13875        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13876            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13877                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13878                return;
13879            }
13880        }
13881
13882        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13883        try {
13884            PackageParser.collectCertificates(pkg, parseFlags);
13885        } catch (PackageParserException e) {
13886            res.setError("Failed collect during installPackageLI", e);
13887            return;
13888        } finally {
13889            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13890        }
13891
13892        // Get rid of all references to package scan path via parser.
13893        pp = null;
13894        String oldCodePath = null;
13895        boolean systemApp = false;
13896        synchronized (mPackages) {
13897            // Check if installing already existing package
13898            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13899                String oldName = mSettings.mRenamedPackages.get(pkgName);
13900                if (pkg.mOriginalPackages != null
13901                        && pkg.mOriginalPackages.contains(oldName)
13902                        && mPackages.containsKey(oldName)) {
13903                    // This package is derived from an original package,
13904                    // and this device has been updating from that original
13905                    // name.  We must continue using the original name, so
13906                    // rename the new package here.
13907                    pkg.setPackageName(oldName);
13908                    pkgName = pkg.packageName;
13909                    replace = true;
13910                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13911                            + oldName + " pkgName=" + pkgName);
13912                } else if (mPackages.containsKey(pkgName)) {
13913                    // This package, under its official name, already exists
13914                    // on the device; we should replace it.
13915                    replace = true;
13916                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13917                }
13918
13919                // Child packages are installed through the parent package
13920                if (pkg.parentPackage != null) {
13921                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13922                            "Package " + pkg.packageName + " is child of package "
13923                                    + pkg.parentPackage.parentPackage + ". Child packages "
13924                                    + "can be updated only through the parent package.");
13925                    return;
13926                }
13927
13928                if (replace) {
13929                    // Prevent apps opting out from runtime permissions
13930                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13931                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13932                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13933                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13934                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13935                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13936                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13937                                        + " doesn't support runtime permissions but the old"
13938                                        + " target SDK " + oldTargetSdk + " does.");
13939                        return;
13940                    }
13941
13942                    // Prevent installing of child packages
13943                    if (oldPackage.parentPackage != null) {
13944                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13945                                "Package " + pkg.packageName + " is child of package "
13946                                        + oldPackage.parentPackage + ". Child packages "
13947                                        + "can be updated only through the parent package.");
13948                        return;
13949                    }
13950                }
13951            }
13952
13953            PackageSetting ps = mSettings.mPackages.get(pkgName);
13954            if (ps != null) {
13955                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13956
13957                // Quick sanity check that we're signed correctly if updating;
13958                // we'll check this again later when scanning, but we want to
13959                // bail early here before tripping over redefined permissions.
13960                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13961                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13962                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13963                                + pkg.packageName + " upgrade keys do not match the "
13964                                + "previously installed version");
13965                        return;
13966                    }
13967                } else {
13968                    try {
13969                        verifySignaturesLP(ps, pkg);
13970                    } catch (PackageManagerException e) {
13971                        res.setError(e.error, e.getMessage());
13972                        return;
13973                    }
13974                }
13975
13976                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13977                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13978                    systemApp = (ps.pkg.applicationInfo.flags &
13979                            ApplicationInfo.FLAG_SYSTEM) != 0;
13980                }
13981                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13982            }
13983
13984            // Check whether the newly-scanned package wants to define an already-defined perm
13985            int N = pkg.permissions.size();
13986            for (int i = N-1; i >= 0; i--) {
13987                PackageParser.Permission perm = pkg.permissions.get(i);
13988                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13989                if (bp != null) {
13990                    // If the defining package is signed with our cert, it's okay.  This
13991                    // also includes the "updating the same package" case, of course.
13992                    // "updating same package" could also involve key-rotation.
13993                    final boolean sigsOk;
13994                    if (bp.sourcePackage.equals(pkg.packageName)
13995                            && (bp.packageSetting instanceof PackageSetting)
13996                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13997                                    scanFlags))) {
13998                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13999                    } else {
14000                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14001                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14002                    }
14003                    if (!sigsOk) {
14004                        // If the owning package is the system itself, we log but allow
14005                        // install to proceed; we fail the install on all other permission
14006                        // redefinitions.
14007                        if (!bp.sourcePackage.equals("android")) {
14008                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14009                                    + pkg.packageName + " attempting to redeclare permission "
14010                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14011                            res.origPermission = perm.info.name;
14012                            res.origPackage = bp.sourcePackage;
14013                            return;
14014                        } else {
14015                            Slog.w(TAG, "Package " + pkg.packageName
14016                                    + " attempting to redeclare system permission "
14017                                    + perm.info.name + "; ignoring new declaration");
14018                            pkg.permissions.remove(i);
14019                        }
14020                    }
14021                }
14022            }
14023        }
14024
14025        if (systemApp) {
14026            if (onExternal) {
14027                // Abort update; system app can't be replaced with app on sdcard
14028                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14029                        "Cannot install updates to system apps on sdcard");
14030                return;
14031            } else if (ephemeral) {
14032                // Abort update; system app can't be replaced with an ephemeral app
14033                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14034                        "Cannot update a system app with an ephemeral app");
14035                return;
14036            }
14037        }
14038
14039        if (args.move != null) {
14040            // We did an in-place move, so dex is ready to roll
14041            scanFlags |= SCAN_NO_DEX;
14042            scanFlags |= SCAN_MOVE;
14043
14044            synchronized (mPackages) {
14045                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14046                if (ps == null) {
14047                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14048                            "Missing settings for moved package " + pkgName);
14049                }
14050
14051                // We moved the entire application as-is, so bring over the
14052                // previously derived ABI information.
14053                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14054                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14055            }
14056
14057        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14058            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14059            scanFlags |= SCAN_NO_DEX;
14060
14061            try {
14062                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14063                    args.abiOverride : pkg.cpuAbiOverride);
14064                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14065                        true /* extract libs */);
14066            } catch (PackageManagerException pme) {
14067                Slog.e(TAG, "Error deriving application ABI", pme);
14068                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14069                return;
14070            }
14071
14072
14073            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14074            // Do not run PackageDexOptimizer through the local performDexOpt
14075            // method because `pkg` is not in `mPackages` yet.
14076            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14077                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14078            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14079            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14080                String msg = "Extracking package failed for " + pkgName;
14081                res.setError(INSTALL_FAILED_DEXOPT, msg);
14082                return;
14083            }
14084        }
14085
14086        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14087            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14088            return;
14089        }
14090
14091        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14092
14093        if (replace) {
14094            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14095                    installerPackageName, res);
14096        } else {
14097            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14098                    args.user, installerPackageName, volumeUuid, res);
14099        }
14100        synchronized (mPackages) {
14101            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14102            if (ps != null) {
14103                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14104            }
14105
14106            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14107            for (int i = 0; i < childCount; i++) {
14108                PackageParser.Package childPkg = pkg.childPackages.get(i);
14109                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14110                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14111                if (childPs != null) {
14112                    childRes.newUsers = childPs.queryInstalledUsers(
14113                            sUserManager.getUserIds(), true);
14114                }
14115            }
14116        }
14117    }
14118
14119    private void startIntentFilterVerifications(int userId, boolean replacing,
14120            PackageParser.Package pkg) {
14121        if (mIntentFilterVerifierComponent == null) {
14122            Slog.w(TAG, "No IntentFilter verification will not be done as "
14123                    + "there is no IntentFilterVerifier available!");
14124            return;
14125        }
14126
14127        final int verifierUid = getPackageUid(
14128                mIntentFilterVerifierComponent.getPackageName(),
14129                MATCH_DEBUG_TRIAGED_MISSING,
14130                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14131
14132        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14133        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14134        mHandler.sendMessage(msg);
14135
14136        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14137        for (int i = 0; i < childCount; i++) {
14138            PackageParser.Package childPkg = pkg.childPackages.get(i);
14139            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14140            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14141            mHandler.sendMessage(msg);
14142        }
14143    }
14144
14145    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14146            PackageParser.Package pkg) {
14147        int size = pkg.activities.size();
14148        if (size == 0) {
14149            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14150                    "No activity, so no need to verify any IntentFilter!");
14151            return;
14152        }
14153
14154        final boolean hasDomainURLs = hasDomainURLs(pkg);
14155        if (!hasDomainURLs) {
14156            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14157                    "No domain URLs, so no need to verify any IntentFilter!");
14158            return;
14159        }
14160
14161        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14162                + " if any IntentFilter from the " + size
14163                + " Activities needs verification ...");
14164
14165        int count = 0;
14166        final String packageName = pkg.packageName;
14167
14168        synchronized (mPackages) {
14169            // If this is a new install and we see that we've already run verification for this
14170            // package, we have nothing to do: it means the state was restored from backup.
14171            if (!replacing) {
14172                IntentFilterVerificationInfo ivi =
14173                        mSettings.getIntentFilterVerificationLPr(packageName);
14174                if (ivi != null) {
14175                    if (DEBUG_DOMAIN_VERIFICATION) {
14176                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14177                                + ivi.getStatusString());
14178                    }
14179                    return;
14180                }
14181            }
14182
14183            // If any filters need to be verified, then all need to be.
14184            boolean needToVerify = false;
14185            for (PackageParser.Activity a : pkg.activities) {
14186                for (ActivityIntentInfo filter : a.intents) {
14187                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14188                        if (DEBUG_DOMAIN_VERIFICATION) {
14189                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14190                        }
14191                        needToVerify = true;
14192                        break;
14193                    }
14194                }
14195            }
14196
14197            if (needToVerify) {
14198                final int verificationId = mIntentFilterVerificationToken++;
14199                for (PackageParser.Activity a : pkg.activities) {
14200                    for (ActivityIntentInfo filter : a.intents) {
14201                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14202                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14203                                    "Verification needed for IntentFilter:" + filter.toString());
14204                            mIntentFilterVerifier.addOneIntentFilterVerification(
14205                                    verifierUid, userId, verificationId, filter, packageName);
14206                            count++;
14207                        }
14208                    }
14209                }
14210            }
14211        }
14212
14213        if (count > 0) {
14214            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14215                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14216                    +  " for userId:" + userId);
14217            mIntentFilterVerifier.startVerifications(userId);
14218        } else {
14219            if (DEBUG_DOMAIN_VERIFICATION) {
14220                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14221            }
14222        }
14223    }
14224
14225    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14226        final ComponentName cn  = filter.activity.getComponentName();
14227        final String packageName = cn.getPackageName();
14228
14229        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14230                packageName);
14231        if (ivi == null) {
14232            return true;
14233        }
14234        int status = ivi.getStatus();
14235        switch (status) {
14236            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14237            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14238                return true;
14239
14240            default:
14241                // Nothing to do
14242                return false;
14243        }
14244    }
14245
14246    private static boolean isMultiArch(ApplicationInfo info) {
14247        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14248    }
14249
14250    private static boolean isExternal(PackageParser.Package pkg) {
14251        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14252    }
14253
14254    private static boolean isExternal(PackageSetting ps) {
14255        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14256    }
14257
14258    private static boolean isEphemeral(PackageParser.Package pkg) {
14259        return pkg.applicationInfo.isEphemeralApp();
14260    }
14261
14262    private static boolean isEphemeral(PackageSetting ps) {
14263        return ps.pkg != null && isEphemeral(ps.pkg);
14264    }
14265
14266    private static boolean isSystemApp(PackageParser.Package pkg) {
14267        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14268    }
14269
14270    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14271        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14272    }
14273
14274    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14275        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14276    }
14277
14278    private static boolean isSystemApp(PackageSetting ps) {
14279        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14280    }
14281
14282    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14283        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14284    }
14285
14286    private int packageFlagsToInstallFlags(PackageSetting ps) {
14287        int installFlags = 0;
14288        if (isEphemeral(ps)) {
14289            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14290        }
14291        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14292            // This existing package was an external ASEC install when we have
14293            // the external flag without a UUID
14294            installFlags |= PackageManager.INSTALL_EXTERNAL;
14295        }
14296        if (ps.isForwardLocked()) {
14297            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14298        }
14299        return installFlags;
14300    }
14301
14302    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14303        if (isExternal(pkg)) {
14304            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14305                return StorageManager.UUID_PRIMARY_PHYSICAL;
14306            } else {
14307                return pkg.volumeUuid;
14308            }
14309        } else {
14310            return StorageManager.UUID_PRIVATE_INTERNAL;
14311        }
14312    }
14313
14314    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14315        if (isExternal(pkg)) {
14316            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14317                return mSettings.getExternalVersion();
14318            } else {
14319                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14320            }
14321        } else {
14322            return mSettings.getInternalVersion();
14323        }
14324    }
14325
14326    private void deleteTempPackageFiles() {
14327        final FilenameFilter filter = new FilenameFilter() {
14328            public boolean accept(File dir, String name) {
14329                return name.startsWith("vmdl") && name.endsWith(".tmp");
14330            }
14331        };
14332        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14333            file.delete();
14334        }
14335    }
14336
14337    @Override
14338    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14339            int flags) {
14340        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14341                flags);
14342    }
14343
14344    @Override
14345    public void deletePackage(final String packageName,
14346            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14347        mContext.enforceCallingOrSelfPermission(
14348                android.Manifest.permission.DELETE_PACKAGES, null);
14349        Preconditions.checkNotNull(packageName);
14350        Preconditions.checkNotNull(observer);
14351        final int uid = Binder.getCallingUid();
14352        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14353        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14354        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14355            mContext.enforceCallingOrSelfPermission(
14356                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14357                    "deletePackage for user " + userId);
14358        }
14359
14360        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14361            try {
14362                observer.onPackageDeleted(packageName,
14363                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14364            } catch (RemoteException re) {
14365            }
14366            return;
14367        }
14368
14369        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14370            try {
14371                observer.onPackageDeleted(packageName,
14372                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14373            } catch (RemoteException re) {
14374            }
14375            return;
14376        }
14377
14378        if (DEBUG_REMOVE) {
14379            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14380                    + " deleteAllUsers: " + deleteAllUsers );
14381        }
14382        // Queue up an async operation since the package deletion may take a little while.
14383        mHandler.post(new Runnable() {
14384            public void run() {
14385                mHandler.removeCallbacks(this);
14386                int returnCode;
14387                if (!deleteAllUsers) {
14388                    returnCode = deletePackageX(packageName, userId, flags);
14389                } else {
14390                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14391                    // If nobody is blocking uninstall, proceed with delete for all users
14392                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14393                        returnCode = deletePackageX(packageName, userId, flags);
14394                    } else {
14395                        // Otherwise uninstall individually for users with blockUninstalls=false
14396                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14397                        for (int userId : users) {
14398                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14399                                returnCode = deletePackageX(packageName, userId, userFlags);
14400                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14401                                    Slog.w(TAG, "Package delete failed for user " + userId
14402                                            + ", returnCode " + returnCode);
14403                                }
14404                            }
14405                        }
14406                        // The app has only been marked uninstalled for certain users.
14407                        // We still need to report that delete was blocked
14408                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14409                    }
14410                }
14411                try {
14412                    observer.onPackageDeleted(packageName, returnCode, null);
14413                } catch (RemoteException e) {
14414                    Log.i(TAG, "Observer no longer exists.");
14415                } //end catch
14416            } //end run
14417        });
14418    }
14419
14420    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14421        int[] result = EMPTY_INT_ARRAY;
14422        for (int userId : userIds) {
14423            if (getBlockUninstallForUser(packageName, userId)) {
14424                result = ArrayUtils.appendInt(result, userId);
14425            }
14426        }
14427        return result;
14428    }
14429
14430    @Override
14431    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14432        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14433    }
14434
14435    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14436        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14437                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14438        try {
14439            if (dpm != null) {
14440                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14441                        /* callingUserOnly =*/ false);
14442                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14443                        : deviceOwnerComponentName.getPackageName();
14444                // Does the package contains the device owner?
14445                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14446                // this check is probably not needed, since DO should be registered as a device
14447                // admin on some user too. (Original bug for this: b/17657954)
14448                if (packageName.equals(deviceOwnerPackageName)) {
14449                    return true;
14450                }
14451                // Does it contain a device admin for any user?
14452                int[] users;
14453                if (userId == UserHandle.USER_ALL) {
14454                    users = sUserManager.getUserIds();
14455                } else {
14456                    users = new int[]{userId};
14457                }
14458                for (int i = 0; i < users.length; ++i) {
14459                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14460                        return true;
14461                    }
14462                }
14463            }
14464        } catch (RemoteException e) {
14465        }
14466        return false;
14467    }
14468
14469    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14470        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14471    }
14472
14473    /**
14474     *  This method is an internal method that could be get invoked either
14475     *  to delete an installed package or to clean up a failed installation.
14476     *  After deleting an installed package, a broadcast is sent to notify any
14477     *  listeners that the package has been installed. For cleaning up a failed
14478     *  installation, the broadcast is not necessary since the package's
14479     *  installation wouldn't have sent the initial broadcast either
14480     *  The key steps in deleting a package are
14481     *  deleting the package information in internal structures like mPackages,
14482     *  deleting the packages base directories through installd
14483     *  updating mSettings to reflect current status
14484     *  persisting settings for later use
14485     *  sending a broadcast if necessary
14486     */
14487    private int deletePackageX(String packageName, int userId, int flags) {
14488        final PackageRemovedInfo info = new PackageRemovedInfo();
14489        final boolean res;
14490
14491        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14492                ? UserHandle.ALL : new UserHandle(userId);
14493
14494        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14495            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14496            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14497        }
14498
14499        PackageSetting uninstalledPs = null;
14500
14501        // for the uninstall-updates case and restricted profiles, remember the per-
14502        // user handle installed state
14503        int[] allUsers;
14504        synchronized (mPackages) {
14505            uninstalledPs = mSettings.mPackages.get(packageName);
14506            if (uninstalledPs == null) {
14507                Slog.w(TAG, "Not removing non-existent package " + packageName);
14508                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14509            }
14510            allUsers = sUserManager.getUserIds();
14511            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14512        }
14513
14514        synchronized (mInstallLock) {
14515            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14516            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14517                    flags | REMOVE_CHATTY, info, true, null);
14518            deleteProfilesLI(packageName, /*destroy*/ true);
14519            synchronized (mPackages) {
14520                if (res) {
14521                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14522                }
14523            }
14524        }
14525
14526        if (res) {
14527            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14528            info.sendPackageRemovedBroadcasts(killApp);
14529            info.sendSystemPackageUpdatedBroadcasts();
14530            info.sendSystemPackageAppearedBroadcasts();
14531        }
14532        // Force a gc here.
14533        Runtime.getRuntime().gc();
14534        // Delete the resources here after sending the broadcast to let
14535        // other processes clean up before deleting resources.
14536        if (info.args != null) {
14537            synchronized (mInstallLock) {
14538                info.args.doPostDeleteLI(true);
14539            }
14540        }
14541
14542        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14543    }
14544
14545    class PackageRemovedInfo {
14546        String removedPackage;
14547        int uid = -1;
14548        int removedAppId = -1;
14549        int[] origUsers;
14550        int[] removedUsers = null;
14551        boolean isRemovedPackageSystemUpdate = false;
14552        boolean isUpdate;
14553        boolean dataRemoved;
14554        boolean removedForAllUsers;
14555        // Clean up resources deleted packages.
14556        InstallArgs args = null;
14557        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14558        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14559
14560        void sendPackageRemovedBroadcasts(boolean killApp) {
14561            sendPackageRemovedBroadcastInternal(killApp);
14562            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14563            for (int i = 0; i < childCount; i++) {
14564                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14565                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14566            }
14567        }
14568
14569        void sendSystemPackageUpdatedBroadcasts() {
14570            if (isRemovedPackageSystemUpdate) {
14571                sendSystemPackageUpdatedBroadcastsInternal();
14572                final int childCount = (removedChildPackages != null)
14573                        ? removedChildPackages.size() : 0;
14574                for (int i = 0; i < childCount; i++) {
14575                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14576                    if (childInfo.isRemovedPackageSystemUpdate) {
14577                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14578                    }
14579                }
14580            }
14581        }
14582
14583        void sendSystemPackageAppearedBroadcasts() {
14584            final int packageCount = (appearedChildPackages != null)
14585                    ? appearedChildPackages.size() : 0;
14586            for (int i = 0; i < packageCount; i++) {
14587                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14588                for (int userId : installedInfo.newUsers) {
14589                    sendPackageAddedForUser(installedInfo.name, true,
14590                            UserHandle.getAppId(installedInfo.uid), userId);
14591                }
14592            }
14593        }
14594
14595        private void sendSystemPackageUpdatedBroadcastsInternal() {
14596            Bundle extras = new Bundle(2);
14597            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14598            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14599            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14600                    extras, 0, null, null, null);
14601            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14602                    extras, 0, null, null, null);
14603            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14604                    null, 0, removedPackage, null, null);
14605        }
14606
14607        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
14608            Bundle extras = new Bundle(2);
14609            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14610            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14611            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
14612            if (isUpdate || isRemovedPackageSystemUpdate) {
14613                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14614            }
14615            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14616            if (removedPackage != null) {
14617                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14618                        extras, 0, null, null, removedUsers);
14619                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14620                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14621                            removedPackage, extras, 0, null, null, removedUsers);
14622                }
14623            }
14624            if (removedAppId >= 0) {
14625                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14626                        removedUsers);
14627            }
14628        }
14629    }
14630
14631    /*
14632     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14633     * flag is not set, the data directory is removed as well.
14634     * make sure this flag is set for partially installed apps. If not its meaningless to
14635     * delete a partially installed application.
14636     */
14637    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14638            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14639        String packageName = ps.name;
14640        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14641        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14642        // Retrieve object to delete permissions for shared user later on
14643        final PackageSetting deletedPs;
14644        // reader
14645        synchronized (mPackages) {
14646            deletedPs = mSettings.mPackages.get(packageName);
14647            if (outInfo != null) {
14648                outInfo.removedPackage = packageName;
14649                outInfo.removedUsers = deletedPs != null
14650                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14651                        : null;
14652            }
14653        }
14654        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14655            removeDataDirsLI(ps.volumeUuid, packageName);
14656            if (outInfo != null) {
14657                outInfo.dataRemoved = true;
14658            }
14659            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14660        }
14661        // writer
14662        synchronized (mPackages) {
14663            if (deletedPs != null) {
14664                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14665                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14666                    clearDefaultBrowserIfNeeded(packageName);
14667                    if (outInfo != null) {
14668                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14669                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14670                    }
14671                    updatePermissionsLPw(deletedPs.name, null, 0);
14672                    if (deletedPs.sharedUser != null) {
14673                        // Remove permissions associated with package. Since runtime
14674                        // permissions are per user we have to kill the removed package
14675                        // or packages running under the shared user of the removed
14676                        // package if revoking the permissions requested only by the removed
14677                        // package is successful and this causes a change in gids.
14678                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14679                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14680                                    userId);
14681                            if (userIdToKill == UserHandle.USER_ALL
14682                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14683                                // If gids changed for this user, kill all affected packages.
14684                                mHandler.post(new Runnable() {
14685                                    @Override
14686                                    public void run() {
14687                                        // This has to happen with no lock held.
14688                                        killApplication(deletedPs.name, deletedPs.appId,
14689                                                KILL_APP_REASON_GIDS_CHANGED);
14690                                    }
14691                                });
14692                                break;
14693                            }
14694                        }
14695                    }
14696                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14697                }
14698                // make sure to preserve per-user disabled state if this removal was just
14699                // a downgrade of a system app to the factory package
14700                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14701                    if (DEBUG_REMOVE) {
14702                        Slog.d(TAG, "Propagating install state across downgrade");
14703                    }
14704                    for (int userId : allUserHandles) {
14705                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14706                        if (DEBUG_REMOVE) {
14707                            Slog.d(TAG, "    user " + userId + " => " + installed);
14708                        }
14709                        ps.setInstalled(installed, userId);
14710                    }
14711                }
14712            }
14713            // can downgrade to reader
14714            if (writeSettings) {
14715                // Save settings now
14716                mSettings.writeLPr();
14717            }
14718        }
14719        if (outInfo != null) {
14720            // A user ID was deleted here. Go through all users and remove it
14721            // from KeyStore.
14722            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14723        }
14724    }
14725
14726    static boolean locationIsPrivileged(File path) {
14727        try {
14728            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14729                    .getCanonicalPath();
14730            return path.getCanonicalPath().startsWith(privilegedAppDir);
14731        } catch (IOException e) {
14732            Slog.e(TAG, "Unable to access code path " + path);
14733        }
14734        return false;
14735    }
14736
14737    /*
14738     * Tries to delete system package.
14739     */
14740    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14741            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14742            boolean writeSettings) {
14743        if (deletedPs.parentPackageName != null) {
14744            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14745            return false;
14746        }
14747
14748        final boolean applyUserRestrictions
14749                = (allUserHandles != null) && (outInfo.origUsers != null);
14750        final PackageSetting disabledPs;
14751        // Confirm if the system package has been updated
14752        // An updated system app can be deleted. This will also have to restore
14753        // the system pkg from system partition
14754        // reader
14755        synchronized (mPackages) {
14756            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
14757        }
14758
14759        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14760                + " disabledPs=" + disabledPs);
14761
14762        if (disabledPs == null) {
14763            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14764            return false;
14765        } else if (DEBUG_REMOVE) {
14766            Slog.d(TAG, "Deleting system pkg from data partition");
14767        }
14768
14769        if (DEBUG_REMOVE) {
14770            if (applyUserRestrictions) {
14771                Slog.d(TAG, "Remembering install states:");
14772                for (int userId : allUserHandles) {
14773                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14774                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14775                }
14776            }
14777        }
14778
14779        // Delete the updated package
14780        outInfo.isRemovedPackageSystemUpdate = true;
14781        if (outInfo.removedChildPackages != null) {
14782            final int childCount = (deletedPs.childPackageNames != null)
14783                    ? deletedPs.childPackageNames.size() : 0;
14784            for (int i = 0; i < childCount; i++) {
14785                String childPackageName = deletedPs.childPackageNames.get(i);
14786                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14787                        .contains(childPackageName)) {
14788                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14789                            childPackageName);
14790                    if (childInfo != null) {
14791                        childInfo.isRemovedPackageSystemUpdate = true;
14792                    }
14793                }
14794            }
14795        }
14796
14797        if (disabledPs.versionCode < deletedPs.versionCode) {
14798            // Delete data for downgrades
14799            flags &= ~PackageManager.DELETE_KEEP_DATA;
14800        } else {
14801            // Preserve data by setting flag
14802            flags |= PackageManager.DELETE_KEEP_DATA;
14803        }
14804
14805        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
14806                outInfo, writeSettings, disabledPs.pkg);
14807        if (!ret) {
14808            return false;
14809        }
14810
14811        // writer
14812        synchronized (mPackages) {
14813            // Reinstate the old system package
14814            enableSystemPackageLPw(disabledPs.pkg);
14815            // Remove any native libraries from the upgraded package.
14816            removeNativeBinariesLI(deletedPs);
14817        }
14818
14819        // Install the system package
14820        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14821        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14822        if (locationIsPrivileged(disabledPs.codePath)) {
14823            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14824        }
14825
14826        final PackageParser.Package newPkg;
14827        try {
14828            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14829        } catch (PackageManagerException e) {
14830            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14831                    + e.getMessage());
14832            return false;
14833        }
14834
14835        prepareAppDataAfterInstall(newPkg);
14836
14837        // writer
14838        synchronized (mPackages) {
14839            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14840
14841            // Propagate the permissions state as we do not want to drop on the floor
14842            // runtime permissions. The update permissions method below will take
14843            // care of removing obsolete permissions and grant install permissions.
14844            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14845            updatePermissionsLPw(newPkg.packageName, newPkg,
14846                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14847
14848            if (applyUserRestrictions) {
14849                if (DEBUG_REMOVE) {
14850                    Slog.d(TAG, "Propagating install state across reinstall");
14851                }
14852                for (int userId : allUserHandles) {
14853                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14854                    if (DEBUG_REMOVE) {
14855                        Slog.d(TAG, "    user " + userId + " => " + installed);
14856                    }
14857                    ps.setInstalled(installed, userId);
14858
14859                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14860                }
14861                // Regardless of writeSettings we need to ensure that this restriction
14862                // state propagation is persisted
14863                mSettings.writeAllUsersPackageRestrictionsLPr();
14864            }
14865            // can downgrade to reader here
14866            if (writeSettings) {
14867                mSettings.writeLPr();
14868            }
14869        }
14870        return true;
14871    }
14872
14873    private boolean deleteInstalledPackageLI(PackageSetting ps,
14874            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14875            PackageRemovedInfo outInfo, boolean writeSettings,
14876            PackageParser.Package replacingPackage) {
14877        synchronized (mPackages) {
14878            if (outInfo != null) {
14879                outInfo.uid = ps.appId;
14880            }
14881
14882            if (outInfo != null && outInfo.removedChildPackages != null) {
14883                final int childCount = (ps.childPackageNames != null)
14884                        ? ps.childPackageNames.size() : 0;
14885                for (int i = 0; i < childCount; i++) {
14886                    String childPackageName = ps.childPackageNames.get(i);
14887                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14888                    if (childPs == null) {
14889                        return false;
14890                    }
14891                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14892                            childPackageName);
14893                    if (childInfo != null) {
14894                        childInfo.uid = childPs.appId;
14895                    }
14896                }
14897            }
14898        }
14899
14900        // Delete package data from internal structures and also remove data if flag is set
14901        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14902
14903        // Delete the child packages data
14904        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14905        for (int i = 0; i < childCount; i++) {
14906            PackageSetting childPs;
14907            synchronized (mPackages) {
14908                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14909            }
14910            if (childPs != null) {
14911                PackageRemovedInfo childOutInfo = (outInfo != null
14912                        && outInfo.removedChildPackages != null)
14913                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14914                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14915                        && (replacingPackage != null
14916                        && !replacingPackage.hasChildPackage(childPs.name))
14917                        ? flags & ~DELETE_KEEP_DATA : flags;
14918                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14919                        deleteFlags, writeSettings);
14920            }
14921        }
14922
14923        // Delete application code and resources only for parent packages
14924        if (ps.parentPackageName == null) {
14925            if (deleteCodeAndResources && (outInfo != null)) {
14926                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14927                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14928                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14929            }
14930        }
14931
14932        return true;
14933    }
14934
14935    @Override
14936    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14937            int userId) {
14938        mContext.enforceCallingOrSelfPermission(
14939                android.Manifest.permission.DELETE_PACKAGES, null);
14940        synchronized (mPackages) {
14941            PackageSetting ps = mSettings.mPackages.get(packageName);
14942            if (ps == null) {
14943                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14944                return false;
14945            }
14946            if (!ps.getInstalled(userId)) {
14947                // Can't block uninstall for an app that is not installed or enabled.
14948                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14949                return false;
14950            }
14951            ps.setBlockUninstall(blockUninstall, userId);
14952            mSettings.writePackageRestrictionsLPr(userId);
14953        }
14954        return true;
14955    }
14956
14957    @Override
14958    public boolean getBlockUninstallForUser(String packageName, int userId) {
14959        synchronized (mPackages) {
14960            PackageSetting ps = mSettings.mPackages.get(packageName);
14961            if (ps == null) {
14962                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14963                return false;
14964            }
14965            return ps.getBlockUninstall(userId);
14966        }
14967    }
14968
14969    @Override
14970    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14971        int callingUid = Binder.getCallingUid();
14972        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14973            throw new SecurityException(
14974                    "setRequiredForSystemUser can only be run by the system or root");
14975        }
14976        synchronized (mPackages) {
14977            PackageSetting ps = mSettings.mPackages.get(packageName);
14978            if (ps == null) {
14979                Log.w(TAG, "Package doesn't exist: " + packageName);
14980                return false;
14981            }
14982            if (systemUserApp) {
14983                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14984            } else {
14985                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14986            }
14987            mSettings.writeLPr();
14988        }
14989        return true;
14990    }
14991
14992    /*
14993     * This method handles package deletion in general
14994     */
14995    private boolean deletePackageLI(String packageName, UserHandle user,
14996            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14997            PackageRemovedInfo outInfo, boolean writeSettings,
14998            PackageParser.Package replacingPackage) {
14999        if (packageName == null) {
15000            Slog.w(TAG, "Attempt to delete null packageName.");
15001            return false;
15002        }
15003
15004        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15005
15006        PackageSetting ps;
15007
15008        synchronized (mPackages) {
15009            ps = mSettings.mPackages.get(packageName);
15010            if (ps == null) {
15011                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15012                return false;
15013            }
15014
15015            if (ps.parentPackageName != null && (!isSystemApp(ps)
15016                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15017                if (DEBUG_REMOVE) {
15018                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15019                            + ((user == null) ? UserHandle.USER_ALL : user));
15020                }
15021                final int removedUserId = (user != null) ? user.getIdentifier()
15022                        : UserHandle.USER_ALL;
15023                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
15024                    return false;
15025                }
15026                markPackageUninstalledForUserLPw(ps, user);
15027                scheduleWritePackageRestrictionsLocked(user);
15028                return true;
15029            }
15030        }
15031
15032        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15033                && user.getIdentifier() != UserHandle.USER_ALL)) {
15034            // The caller is asking that the package only be deleted for a single
15035            // user.  To do this, we just mark its uninstalled state and delete
15036            // its data. If this is a system app, we only allow this to happen if
15037            // they have set the special DELETE_SYSTEM_APP which requests different
15038            // semantics than normal for uninstalling system apps.
15039            markPackageUninstalledForUserLPw(ps, user);
15040
15041            if (!isSystemApp(ps)) {
15042                // Do not uninstall the APK if an app should be cached
15043                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15044                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15045                    // Other user still have this package installed, so all
15046                    // we need to do is clear this user's data and save that
15047                    // it is uninstalled.
15048                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15049                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15050                        return false;
15051                    }
15052                    scheduleWritePackageRestrictionsLocked(user);
15053                    return true;
15054                } else {
15055                    // We need to set it back to 'installed' so the uninstall
15056                    // broadcasts will be sent correctly.
15057                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15058                    ps.setInstalled(true, user.getIdentifier());
15059                }
15060            } else {
15061                // This is a system app, so we assume that the
15062                // other users still have this package installed, so all
15063                // we need to do is clear this user's data and save that
15064                // it is uninstalled.
15065                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15066                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15067                    return false;
15068                }
15069                scheduleWritePackageRestrictionsLocked(user);
15070                return true;
15071            }
15072        }
15073
15074        // If we are deleting a composite package for all users, keep track
15075        // of result for each child.
15076        if (ps.childPackageNames != null && outInfo != null) {
15077            synchronized (mPackages) {
15078                final int childCount = ps.childPackageNames.size();
15079                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15080                for (int i = 0; i < childCount; i++) {
15081                    String childPackageName = ps.childPackageNames.get(i);
15082                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15083                    childInfo.removedPackage = childPackageName;
15084                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15085                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15086                    if (childPs != null) {
15087                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15088                    }
15089                }
15090            }
15091        }
15092
15093        boolean ret = false;
15094        if (isSystemApp(ps)) {
15095            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15096            // When an updated system application is deleted we delete the existing resources
15097            // as well and fall back to existing code in system partition
15098            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15099        } else {
15100            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15101            // Kill application pre-emptively especially for apps on sd.
15102            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15103            if (killApp) {
15104                killApplication(packageName, ps.appId, "uninstall pkg");
15105            }
15106            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
15107                    outInfo, writeSettings, replacingPackage);
15108        }
15109
15110        // Take a note whether we deleted the package for all users
15111        if (outInfo != null) {
15112            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15113            if (outInfo.removedChildPackages != null) {
15114                synchronized (mPackages) {
15115                    final int childCount = outInfo.removedChildPackages.size();
15116                    for (int i = 0; i < childCount; i++) {
15117                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15118                        if (childInfo != null) {
15119                            childInfo.removedForAllUsers = mPackages.get(
15120                                    childInfo.removedPackage) == null;
15121                        }
15122                    }
15123                }
15124            }
15125            // If we uninstalled an update to a system app there may be some
15126            // child packages that appeared as they are declared in the system
15127            // app but were not declared in the update.
15128            if (isSystemApp(ps)) {
15129                synchronized (mPackages) {
15130                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15131                    final int childCount = (updatedPs.childPackageNames != null)
15132                            ? updatedPs.childPackageNames.size() : 0;
15133                    for (int i = 0; i < childCount; i++) {
15134                        String childPackageName = updatedPs.childPackageNames.get(i);
15135                        if (outInfo.removedChildPackages == null
15136                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15137                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15138                            if (childPs == null) {
15139                                continue;
15140                            }
15141                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15142                            installRes.name = childPackageName;
15143                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15144                            installRes.pkg = mPackages.get(childPackageName);
15145                            installRes.uid = childPs.pkg.applicationInfo.uid;
15146                            if (outInfo.appearedChildPackages == null) {
15147                                outInfo.appearedChildPackages = new ArrayMap<>();
15148                            }
15149                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15150                        }
15151                    }
15152                }
15153            }
15154        }
15155
15156        return ret;
15157    }
15158
15159    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15160        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15161                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15162        for (int nextUserId : userIds) {
15163            if (DEBUG_REMOVE) {
15164                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15165            }
15166            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
15167                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15168                    false /*hidden*/, false /*suspended*/, null, null, null,
15169                    false /*blockUninstall*/,
15170                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15171        }
15172    }
15173
15174    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15175            PackageRemovedInfo outInfo) {
15176        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15177                : new int[] {userId};
15178        for (int nextUserId : userIds) {
15179            if (DEBUG_REMOVE) {
15180                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15181                        + nextUserId);
15182            }
15183            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15184            try {
15185                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15186            } catch (InstallerException e) {
15187                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15188                return false;
15189            }
15190            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15191            schedulePackageCleaning(ps.name, nextUserId, false);
15192            synchronized (mPackages) {
15193                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15194                    scheduleWritePackageRestrictionsLocked(nextUserId);
15195                }
15196                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15197            }
15198        }
15199
15200        if (outInfo != null) {
15201            outInfo.removedPackage = ps.name;
15202            outInfo.removedAppId = ps.appId;
15203            outInfo.removedUsers = userIds;
15204        }
15205
15206        return true;
15207    }
15208
15209    private final class ClearStorageConnection implements ServiceConnection {
15210        IMediaContainerService mContainerService;
15211
15212        @Override
15213        public void onServiceConnected(ComponentName name, IBinder service) {
15214            synchronized (this) {
15215                mContainerService = IMediaContainerService.Stub.asInterface(service);
15216                notifyAll();
15217            }
15218        }
15219
15220        @Override
15221        public void onServiceDisconnected(ComponentName name) {
15222        }
15223    }
15224
15225    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15226        final boolean mounted;
15227        if (Environment.isExternalStorageEmulated()) {
15228            mounted = true;
15229        } else {
15230            final String status = Environment.getExternalStorageState();
15231
15232            mounted = status.equals(Environment.MEDIA_MOUNTED)
15233                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15234        }
15235
15236        if (!mounted) {
15237            return;
15238        }
15239
15240        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15241        int[] users;
15242        if (userId == UserHandle.USER_ALL) {
15243            users = sUserManager.getUserIds();
15244        } else {
15245            users = new int[] { userId };
15246        }
15247        final ClearStorageConnection conn = new ClearStorageConnection();
15248        if (mContext.bindServiceAsUser(
15249                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15250            try {
15251                for (int curUser : users) {
15252                    long timeout = SystemClock.uptimeMillis() + 5000;
15253                    synchronized (conn) {
15254                        long now = SystemClock.uptimeMillis();
15255                        while (conn.mContainerService == null && now < timeout) {
15256                            try {
15257                                conn.wait(timeout - now);
15258                            } catch (InterruptedException e) {
15259                            }
15260                        }
15261                    }
15262                    if (conn.mContainerService == null) {
15263                        return;
15264                    }
15265
15266                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15267                    clearDirectory(conn.mContainerService,
15268                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15269                    if (allData) {
15270                        clearDirectory(conn.mContainerService,
15271                                userEnv.buildExternalStorageAppDataDirs(packageName));
15272                        clearDirectory(conn.mContainerService,
15273                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15274                    }
15275                }
15276            } finally {
15277                mContext.unbindService(conn);
15278            }
15279        }
15280    }
15281
15282    @Override
15283    public void clearApplicationProfileData(String packageName) {
15284        enforceSystemOrRoot("Only the system can clear all profile data");
15285        try {
15286            mInstaller.clearAppProfiles(packageName);
15287        } catch (InstallerException ex) {
15288            Log.e(TAG, "Could not clear profile data of package " + packageName);
15289        }
15290    }
15291
15292    @Override
15293    public void clearApplicationUserData(final String packageName,
15294            final IPackageDataObserver observer, final int userId) {
15295        mContext.enforceCallingOrSelfPermission(
15296                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15297
15298        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15299                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15300
15301        final DevicePolicyManagerInternal dpmi = LocalServices
15302                .getService(DevicePolicyManagerInternal.class);
15303        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15304            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15305        }
15306        // Queue up an async operation since the package deletion may take a little while.
15307        mHandler.post(new Runnable() {
15308            public void run() {
15309                mHandler.removeCallbacks(this);
15310                final boolean succeeded;
15311                synchronized (mInstallLock) {
15312                    succeeded = clearApplicationUserDataLI(packageName, userId);
15313                }
15314                clearExternalStorageDataSync(packageName, userId, true);
15315                if (succeeded) {
15316                    // invoke DeviceStorageMonitor's update method to clear any notifications
15317                    DeviceStorageMonitorInternal dsm = LocalServices
15318                            .getService(DeviceStorageMonitorInternal.class);
15319                    if (dsm != null) {
15320                        dsm.checkMemory();
15321                    }
15322                }
15323                if(observer != null) {
15324                    try {
15325                        observer.onRemoveCompleted(packageName, succeeded);
15326                    } catch (RemoteException e) {
15327                        Log.i(TAG, "Observer no longer exists.");
15328                    }
15329                } //end if observer
15330            } //end run
15331        });
15332    }
15333
15334    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15335        if (packageName == null) {
15336            Slog.w(TAG, "Attempt to delete null packageName.");
15337            return false;
15338        }
15339
15340        // Try finding details about the requested package
15341        PackageParser.Package pkg;
15342        synchronized (mPackages) {
15343            pkg = mPackages.get(packageName);
15344            if (pkg == null) {
15345                final PackageSetting ps = mSettings.mPackages.get(packageName);
15346                if (ps != null) {
15347                    pkg = ps.pkg;
15348                }
15349            }
15350
15351            if (pkg == null) {
15352                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15353                return false;
15354            }
15355
15356            PackageSetting ps = (PackageSetting) pkg.mExtras;
15357            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15358        }
15359
15360        // Always delete data directories for package, even if we found no other
15361        // record of app. This helps users recover from UID mismatches without
15362        // resorting to a full data wipe.
15363        // TODO: triage flags as part of 26466827
15364        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15365        try {
15366            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15367        } catch (InstallerException e) {
15368            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15369            return false;
15370        }
15371
15372        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15373        removeKeystoreDataIfNeeded(userId, appId);
15374
15375        // Create a native library symlink only if we have native libraries
15376        // and if the native libraries are 32 bit libraries. We do not provide
15377        // this symlink for 64 bit libraries.
15378        if (pkg.applicationInfo.primaryCpuAbi != null &&
15379                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15380            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15381            try {
15382                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15383                        nativeLibPath, userId);
15384            } catch (InstallerException e) {
15385                Slog.w(TAG, "Failed linking native library dir", e);
15386                return false;
15387            }
15388        }
15389
15390        return true;
15391    }
15392
15393    /**
15394     * Reverts user permission state changes (permissions and flags) in
15395     * all packages for a given user.
15396     *
15397     * @param userId The device user for which to do a reset.
15398     */
15399    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15400        final int packageCount = mPackages.size();
15401        for (int i = 0; i < packageCount; i++) {
15402            PackageParser.Package pkg = mPackages.valueAt(i);
15403            PackageSetting ps = (PackageSetting) pkg.mExtras;
15404            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15405        }
15406    }
15407
15408    /**
15409     * Reverts user permission state changes (permissions and flags).
15410     *
15411     * @param ps The package for which to reset.
15412     * @param userId The device user for which to do a reset.
15413     */
15414    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15415            final PackageSetting ps, final int userId) {
15416        if (ps.pkg == null) {
15417            return;
15418        }
15419
15420        // These are flags that can change base on user actions.
15421        final int userSettableMask = FLAG_PERMISSION_USER_SET
15422                | FLAG_PERMISSION_USER_FIXED
15423                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15424                | FLAG_PERMISSION_REVIEW_REQUIRED;
15425
15426        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15427                | FLAG_PERMISSION_POLICY_FIXED;
15428
15429        boolean writeInstallPermissions = false;
15430        boolean writeRuntimePermissions = false;
15431
15432        final int permissionCount = ps.pkg.requestedPermissions.size();
15433        for (int i = 0; i < permissionCount; i++) {
15434            String permission = ps.pkg.requestedPermissions.get(i);
15435
15436            BasePermission bp = mSettings.mPermissions.get(permission);
15437            if (bp == null) {
15438                continue;
15439            }
15440
15441            // If shared user we just reset the state to which only this app contributed.
15442            if (ps.sharedUser != null) {
15443                boolean used = false;
15444                final int packageCount = ps.sharedUser.packages.size();
15445                for (int j = 0; j < packageCount; j++) {
15446                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15447                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15448                            && pkg.pkg.requestedPermissions.contains(permission)) {
15449                        used = true;
15450                        break;
15451                    }
15452                }
15453                if (used) {
15454                    continue;
15455                }
15456            }
15457
15458            PermissionsState permissionsState = ps.getPermissionsState();
15459
15460            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15461
15462            // Always clear the user settable flags.
15463            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15464                    bp.name) != null;
15465            // If permission review is enabled and this is a legacy app, mark the
15466            // permission as requiring a review as this is the initial state.
15467            int flags = 0;
15468            if (Build.PERMISSIONS_REVIEW_REQUIRED
15469                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15470                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15471            }
15472            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15473                if (hasInstallState) {
15474                    writeInstallPermissions = true;
15475                } else {
15476                    writeRuntimePermissions = true;
15477                }
15478            }
15479
15480            // Below is only runtime permission handling.
15481            if (!bp.isRuntime()) {
15482                continue;
15483            }
15484
15485            // Never clobber system or policy.
15486            if ((oldFlags & policyOrSystemFlags) != 0) {
15487                continue;
15488            }
15489
15490            // If this permission was granted by default, make sure it is.
15491            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15492                if (permissionsState.grantRuntimePermission(bp, userId)
15493                        != PERMISSION_OPERATION_FAILURE) {
15494                    writeRuntimePermissions = true;
15495                }
15496            // If permission review is enabled the permissions for a legacy apps
15497            // are represented as constantly granted runtime ones, so don't revoke.
15498            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15499                // Otherwise, reset the permission.
15500                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15501                switch (revokeResult) {
15502                    case PERMISSION_OPERATION_SUCCESS: {
15503                        writeRuntimePermissions = true;
15504                    } break;
15505
15506                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15507                        writeRuntimePermissions = true;
15508                        final int appId = ps.appId;
15509                        mHandler.post(new Runnable() {
15510                            @Override
15511                            public void run() {
15512                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15513                            }
15514                        });
15515                    } break;
15516                }
15517            }
15518        }
15519
15520        // Synchronously write as we are taking permissions away.
15521        if (writeRuntimePermissions) {
15522            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15523        }
15524
15525        // Synchronously write as we are taking permissions away.
15526        if (writeInstallPermissions) {
15527            mSettings.writeLPr();
15528        }
15529    }
15530
15531    /**
15532     * Remove entries from the keystore daemon. Will only remove it if the
15533     * {@code appId} is valid.
15534     */
15535    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15536        if (appId < 0) {
15537            return;
15538        }
15539
15540        final KeyStore keyStore = KeyStore.getInstance();
15541        if (keyStore != null) {
15542            if (userId == UserHandle.USER_ALL) {
15543                for (final int individual : sUserManager.getUserIds()) {
15544                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15545                }
15546            } else {
15547                keyStore.clearUid(UserHandle.getUid(userId, appId));
15548            }
15549        } else {
15550            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15551        }
15552    }
15553
15554    @Override
15555    public void deleteApplicationCacheFiles(final String packageName,
15556            final IPackageDataObserver observer) {
15557        mContext.enforceCallingOrSelfPermission(
15558                android.Manifest.permission.DELETE_CACHE_FILES, null);
15559        // Queue up an async operation since the package deletion may take a little while.
15560        final int userId = UserHandle.getCallingUserId();
15561        mHandler.post(new Runnable() {
15562            public void run() {
15563                mHandler.removeCallbacks(this);
15564                final boolean succeded;
15565                synchronized (mInstallLock) {
15566                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15567                }
15568                clearExternalStorageDataSync(packageName, userId, false);
15569                if (observer != null) {
15570                    try {
15571                        observer.onRemoveCompleted(packageName, succeded);
15572                    } catch (RemoteException e) {
15573                        Log.i(TAG, "Observer no longer exists.");
15574                    }
15575                } //end if observer
15576            } //end run
15577        });
15578    }
15579
15580    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15581        if (packageName == null) {
15582            Slog.w(TAG, "Attempt to delete null packageName.");
15583            return false;
15584        }
15585        PackageParser.Package p;
15586        synchronized (mPackages) {
15587            p = mPackages.get(packageName);
15588        }
15589        if (p == null) {
15590            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15591            return false;
15592        }
15593        final ApplicationInfo applicationInfo = p.applicationInfo;
15594        if (applicationInfo == null) {
15595            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15596            return false;
15597        }
15598        // TODO: triage flags as part of 26466827
15599        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15600        try {
15601            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15602                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15603        } catch (InstallerException e) {
15604            Slog.w(TAG, "Couldn't remove cache files for package "
15605                    + packageName + " u" + userId, e);
15606            return false;
15607        }
15608        return true;
15609    }
15610
15611    @Override
15612    public void getPackageSizeInfo(final String packageName, int userHandle,
15613            final IPackageStatsObserver observer) {
15614        mContext.enforceCallingOrSelfPermission(
15615                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15616        if (packageName == null) {
15617            throw new IllegalArgumentException("Attempt to get size of null packageName");
15618        }
15619
15620        PackageStats stats = new PackageStats(packageName, userHandle);
15621
15622        /*
15623         * Queue up an async operation since the package measurement may take a
15624         * little while.
15625         */
15626        Message msg = mHandler.obtainMessage(INIT_COPY);
15627        msg.obj = new MeasureParams(stats, observer);
15628        mHandler.sendMessage(msg);
15629    }
15630
15631    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15632            PackageStats pStats) {
15633        if (packageName == null) {
15634            Slog.w(TAG, "Attempt to get size of null packageName.");
15635            return false;
15636        }
15637        PackageParser.Package p;
15638        boolean dataOnly = false;
15639        String libDirRoot = null;
15640        String asecPath = null;
15641        PackageSetting ps = null;
15642        synchronized (mPackages) {
15643            p = mPackages.get(packageName);
15644            ps = mSettings.mPackages.get(packageName);
15645            if(p == null) {
15646                dataOnly = true;
15647                if((ps == null) || (ps.pkg == null)) {
15648                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15649                    return false;
15650                }
15651                p = ps.pkg;
15652            }
15653            if (ps != null) {
15654                libDirRoot = ps.legacyNativeLibraryPathString;
15655            }
15656            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15657                final long token = Binder.clearCallingIdentity();
15658                try {
15659                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15660                    if (secureContainerId != null) {
15661                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15662                    }
15663                } finally {
15664                    Binder.restoreCallingIdentity(token);
15665                }
15666            }
15667        }
15668        String publicSrcDir = null;
15669        if(!dataOnly) {
15670            final ApplicationInfo applicationInfo = p.applicationInfo;
15671            if (applicationInfo == null) {
15672                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15673                return false;
15674            }
15675            if (p.isForwardLocked()) {
15676                publicSrcDir = applicationInfo.getBaseResourcePath();
15677            }
15678        }
15679        // TODO: extend to measure size of split APKs
15680        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15681        // not just the first level.
15682        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15683        // just the primary.
15684        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15685
15686        String apkPath;
15687        File packageDir = new File(p.codePath);
15688
15689        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15690            apkPath = packageDir.getAbsolutePath();
15691            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15692            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15693                libDirRoot = null;
15694            }
15695        } else {
15696            apkPath = p.baseCodePath;
15697        }
15698
15699        // TODO: triage flags as part of 26466827
15700        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15701        try {
15702            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15703                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15704        } catch (InstallerException e) {
15705            return false;
15706        }
15707
15708        // Fix-up for forward-locked applications in ASEC containers.
15709        if (!isExternal(p)) {
15710            pStats.codeSize += pStats.externalCodeSize;
15711            pStats.externalCodeSize = 0L;
15712        }
15713
15714        return true;
15715    }
15716
15717    private int getUidTargetSdkVersionLockedLPr(int uid) {
15718        Object obj = mSettings.getUserIdLPr(uid);
15719        if (obj instanceof SharedUserSetting) {
15720            final SharedUserSetting sus = (SharedUserSetting) obj;
15721            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15722            final Iterator<PackageSetting> it = sus.packages.iterator();
15723            while (it.hasNext()) {
15724                final PackageSetting ps = it.next();
15725                if (ps.pkg != null) {
15726                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15727                    if (v < vers) vers = v;
15728                }
15729            }
15730            return vers;
15731        } else if (obj instanceof PackageSetting) {
15732            final PackageSetting ps = (PackageSetting) obj;
15733            if (ps.pkg != null) {
15734                return ps.pkg.applicationInfo.targetSdkVersion;
15735            }
15736        }
15737        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15738    }
15739
15740    @Override
15741    public void addPreferredActivity(IntentFilter filter, int match,
15742            ComponentName[] set, ComponentName activity, int userId) {
15743        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15744                "Adding preferred");
15745    }
15746
15747    private void addPreferredActivityInternal(IntentFilter filter, int match,
15748            ComponentName[] set, ComponentName activity, boolean always, int userId,
15749            String opname) {
15750        // writer
15751        int callingUid = Binder.getCallingUid();
15752        enforceCrossUserPermission(callingUid, userId,
15753                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
15754        if (filter.countActions() == 0) {
15755            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15756            return;
15757        }
15758        synchronized (mPackages) {
15759            if (mContext.checkCallingOrSelfPermission(
15760                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15761                    != PackageManager.PERMISSION_GRANTED) {
15762                if (getUidTargetSdkVersionLockedLPr(callingUid)
15763                        < Build.VERSION_CODES.FROYO) {
15764                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15765                            + callingUid);
15766                    return;
15767                }
15768                mContext.enforceCallingOrSelfPermission(
15769                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15770            }
15771
15772            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15773            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15774                    + userId + ":");
15775            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15776            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15777            scheduleWritePackageRestrictionsLocked(userId);
15778        }
15779    }
15780
15781    @Override
15782    public void replacePreferredActivity(IntentFilter filter, int match,
15783            ComponentName[] set, ComponentName activity, int userId) {
15784        if (filter.countActions() != 1) {
15785            throw new IllegalArgumentException(
15786                    "replacePreferredActivity expects filter to have only 1 action.");
15787        }
15788        if (filter.countDataAuthorities() != 0
15789                || filter.countDataPaths() != 0
15790                || filter.countDataSchemes() > 1
15791                || filter.countDataTypes() != 0) {
15792            throw new IllegalArgumentException(
15793                    "replacePreferredActivity expects filter to have no data authorities, " +
15794                    "paths, or types; and at most one scheme.");
15795        }
15796
15797        final int callingUid = Binder.getCallingUid();
15798        enforceCrossUserPermission(callingUid, userId,
15799                true /* requireFullPermission */, false /* checkShell */,
15800                "replace preferred activity");
15801        synchronized (mPackages) {
15802            if (mContext.checkCallingOrSelfPermission(
15803                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15804                    != PackageManager.PERMISSION_GRANTED) {
15805                if (getUidTargetSdkVersionLockedLPr(callingUid)
15806                        < Build.VERSION_CODES.FROYO) {
15807                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15808                            + Binder.getCallingUid());
15809                    return;
15810                }
15811                mContext.enforceCallingOrSelfPermission(
15812                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15813            }
15814
15815            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15816            if (pir != null) {
15817                // Get all of the existing entries that exactly match this filter.
15818                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15819                if (existing != null && existing.size() == 1) {
15820                    PreferredActivity cur = existing.get(0);
15821                    if (DEBUG_PREFERRED) {
15822                        Slog.i(TAG, "Checking replace of preferred:");
15823                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15824                        if (!cur.mPref.mAlways) {
15825                            Slog.i(TAG, "  -- CUR; not mAlways!");
15826                        } else {
15827                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15828                            Slog.i(TAG, "  -- CUR: mSet="
15829                                    + Arrays.toString(cur.mPref.mSetComponents));
15830                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15831                            Slog.i(TAG, "  -- NEW: mMatch="
15832                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15833                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15834                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15835                        }
15836                    }
15837                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15838                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15839                            && cur.mPref.sameSet(set)) {
15840                        // Setting the preferred activity to what it happens to be already
15841                        if (DEBUG_PREFERRED) {
15842                            Slog.i(TAG, "Replacing with same preferred activity "
15843                                    + cur.mPref.mShortComponent + " for user "
15844                                    + userId + ":");
15845                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15846                        }
15847                        return;
15848                    }
15849                }
15850
15851                if (existing != null) {
15852                    if (DEBUG_PREFERRED) {
15853                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15854                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15855                    }
15856                    for (int i = 0; i < existing.size(); i++) {
15857                        PreferredActivity pa = existing.get(i);
15858                        if (DEBUG_PREFERRED) {
15859                            Slog.i(TAG, "Removing existing preferred activity "
15860                                    + pa.mPref.mComponent + ":");
15861                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15862                        }
15863                        pir.removeFilter(pa);
15864                    }
15865                }
15866            }
15867            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15868                    "Replacing preferred");
15869        }
15870    }
15871
15872    @Override
15873    public void clearPackagePreferredActivities(String packageName) {
15874        final int uid = Binder.getCallingUid();
15875        // writer
15876        synchronized (mPackages) {
15877            PackageParser.Package pkg = mPackages.get(packageName);
15878            if (pkg == null || pkg.applicationInfo.uid != uid) {
15879                if (mContext.checkCallingOrSelfPermission(
15880                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15881                        != PackageManager.PERMISSION_GRANTED) {
15882                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15883                            < Build.VERSION_CODES.FROYO) {
15884                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15885                                + Binder.getCallingUid());
15886                        return;
15887                    }
15888                    mContext.enforceCallingOrSelfPermission(
15889                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15890                }
15891            }
15892
15893            int user = UserHandle.getCallingUserId();
15894            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15895                scheduleWritePackageRestrictionsLocked(user);
15896            }
15897        }
15898    }
15899
15900    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15901    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15902        ArrayList<PreferredActivity> removed = null;
15903        boolean changed = false;
15904        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15905            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15906            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15907            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15908                continue;
15909            }
15910            Iterator<PreferredActivity> it = pir.filterIterator();
15911            while (it.hasNext()) {
15912                PreferredActivity pa = it.next();
15913                // Mark entry for removal only if it matches the package name
15914                // and the entry is of type "always".
15915                if (packageName == null ||
15916                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15917                                && pa.mPref.mAlways)) {
15918                    if (removed == null) {
15919                        removed = new ArrayList<PreferredActivity>();
15920                    }
15921                    removed.add(pa);
15922                }
15923            }
15924            if (removed != null) {
15925                for (int j=0; j<removed.size(); j++) {
15926                    PreferredActivity pa = removed.get(j);
15927                    pir.removeFilter(pa);
15928                }
15929                changed = true;
15930            }
15931        }
15932        return changed;
15933    }
15934
15935    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15936    private void clearIntentFilterVerificationsLPw(int userId) {
15937        final int packageCount = mPackages.size();
15938        for (int i = 0; i < packageCount; i++) {
15939            PackageParser.Package pkg = mPackages.valueAt(i);
15940            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15941        }
15942    }
15943
15944    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15945    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15946        if (userId == UserHandle.USER_ALL) {
15947            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15948                    sUserManager.getUserIds())) {
15949                for (int oneUserId : sUserManager.getUserIds()) {
15950                    scheduleWritePackageRestrictionsLocked(oneUserId);
15951                }
15952            }
15953        } else {
15954            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15955                scheduleWritePackageRestrictionsLocked(userId);
15956            }
15957        }
15958    }
15959
15960    void clearDefaultBrowserIfNeeded(String packageName) {
15961        for (int oneUserId : sUserManager.getUserIds()) {
15962            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15963            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15964            if (packageName.equals(defaultBrowserPackageName)) {
15965                setDefaultBrowserPackageName(null, oneUserId);
15966            }
15967        }
15968    }
15969
15970    @Override
15971    public void resetApplicationPreferences(int userId) {
15972        mContext.enforceCallingOrSelfPermission(
15973                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15974        // writer
15975        synchronized (mPackages) {
15976            final long identity = Binder.clearCallingIdentity();
15977            try {
15978                clearPackagePreferredActivitiesLPw(null, userId);
15979                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15980                // TODO: We have to reset the default SMS and Phone. This requires
15981                // significant refactoring to keep all default apps in the package
15982                // manager (cleaner but more work) or have the services provide
15983                // callbacks to the package manager to request a default app reset.
15984                applyFactoryDefaultBrowserLPw(userId);
15985                clearIntentFilterVerificationsLPw(userId);
15986                primeDomainVerificationsLPw(userId);
15987                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15988                scheduleWritePackageRestrictionsLocked(userId);
15989            } finally {
15990                Binder.restoreCallingIdentity(identity);
15991            }
15992        }
15993    }
15994
15995    @Override
15996    public int getPreferredActivities(List<IntentFilter> outFilters,
15997            List<ComponentName> outActivities, String packageName) {
15998
15999        int num = 0;
16000        final int userId = UserHandle.getCallingUserId();
16001        // reader
16002        synchronized (mPackages) {
16003            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16004            if (pir != null) {
16005                final Iterator<PreferredActivity> it = pir.filterIterator();
16006                while (it.hasNext()) {
16007                    final PreferredActivity pa = it.next();
16008                    if (packageName == null
16009                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16010                                    && pa.mPref.mAlways)) {
16011                        if (outFilters != null) {
16012                            outFilters.add(new IntentFilter(pa));
16013                        }
16014                        if (outActivities != null) {
16015                            outActivities.add(pa.mPref.mComponent);
16016                        }
16017                    }
16018                }
16019            }
16020        }
16021
16022        return num;
16023    }
16024
16025    @Override
16026    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16027            int userId) {
16028        int callingUid = Binder.getCallingUid();
16029        if (callingUid != Process.SYSTEM_UID) {
16030            throw new SecurityException(
16031                    "addPersistentPreferredActivity can only be run by the system");
16032        }
16033        if (filter.countActions() == 0) {
16034            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16035            return;
16036        }
16037        synchronized (mPackages) {
16038            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16039                    ":");
16040            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16041            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16042                    new PersistentPreferredActivity(filter, activity));
16043            scheduleWritePackageRestrictionsLocked(userId);
16044        }
16045    }
16046
16047    @Override
16048    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16049        int callingUid = Binder.getCallingUid();
16050        if (callingUid != Process.SYSTEM_UID) {
16051            throw new SecurityException(
16052                    "clearPackagePersistentPreferredActivities can only be run by the system");
16053        }
16054        ArrayList<PersistentPreferredActivity> removed = null;
16055        boolean changed = false;
16056        synchronized (mPackages) {
16057            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16058                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16059                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16060                        .valueAt(i);
16061                if (userId != thisUserId) {
16062                    continue;
16063                }
16064                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16065                while (it.hasNext()) {
16066                    PersistentPreferredActivity ppa = it.next();
16067                    // Mark entry for removal only if it matches the package name.
16068                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16069                        if (removed == null) {
16070                            removed = new ArrayList<PersistentPreferredActivity>();
16071                        }
16072                        removed.add(ppa);
16073                    }
16074                }
16075                if (removed != null) {
16076                    for (int j=0; j<removed.size(); j++) {
16077                        PersistentPreferredActivity ppa = removed.get(j);
16078                        ppir.removeFilter(ppa);
16079                    }
16080                    changed = true;
16081                }
16082            }
16083
16084            if (changed) {
16085                scheduleWritePackageRestrictionsLocked(userId);
16086            }
16087        }
16088    }
16089
16090    /**
16091     * Common machinery for picking apart a restored XML blob and passing
16092     * it to a caller-supplied functor to be applied to the running system.
16093     */
16094    private void restoreFromXml(XmlPullParser parser, int userId,
16095            String expectedStartTag, BlobXmlRestorer functor)
16096            throws IOException, XmlPullParserException {
16097        int type;
16098        while ((type = parser.next()) != XmlPullParser.START_TAG
16099                && type != XmlPullParser.END_DOCUMENT) {
16100        }
16101        if (type != XmlPullParser.START_TAG) {
16102            // oops didn't find a start tag?!
16103            if (DEBUG_BACKUP) {
16104                Slog.e(TAG, "Didn't find start tag during restore");
16105            }
16106            return;
16107        }
16108Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16109        // this is supposed to be TAG_PREFERRED_BACKUP
16110        if (!expectedStartTag.equals(parser.getName())) {
16111            if (DEBUG_BACKUP) {
16112                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16113            }
16114            return;
16115        }
16116
16117        // skip interfering stuff, then we're aligned with the backing implementation
16118        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16119Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16120        functor.apply(parser, userId);
16121    }
16122
16123    private interface BlobXmlRestorer {
16124        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16125    }
16126
16127    /**
16128     * Non-Binder method, support for the backup/restore mechanism: write the
16129     * full set of preferred activities in its canonical XML format.  Returns the
16130     * XML output as a byte array, or null if there is none.
16131     */
16132    @Override
16133    public byte[] getPreferredActivityBackup(int userId) {
16134        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16135            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16136        }
16137
16138        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16139        try {
16140            final XmlSerializer serializer = new FastXmlSerializer();
16141            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16142            serializer.startDocument(null, true);
16143            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16144
16145            synchronized (mPackages) {
16146                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16147            }
16148
16149            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16150            serializer.endDocument();
16151            serializer.flush();
16152        } catch (Exception e) {
16153            if (DEBUG_BACKUP) {
16154                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16155            }
16156            return null;
16157        }
16158
16159        return dataStream.toByteArray();
16160    }
16161
16162    @Override
16163    public void restorePreferredActivities(byte[] backup, int userId) {
16164        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16165            throw new SecurityException("Only the system may call restorePreferredActivities()");
16166        }
16167
16168        try {
16169            final XmlPullParser parser = Xml.newPullParser();
16170            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16171            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16172                    new BlobXmlRestorer() {
16173                        @Override
16174                        public void apply(XmlPullParser parser, int userId)
16175                                throws XmlPullParserException, IOException {
16176                            synchronized (mPackages) {
16177                                mSettings.readPreferredActivitiesLPw(parser, userId);
16178                            }
16179                        }
16180                    } );
16181        } catch (Exception e) {
16182            if (DEBUG_BACKUP) {
16183                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16184            }
16185        }
16186    }
16187
16188    /**
16189     * Non-Binder method, support for the backup/restore mechanism: write the
16190     * default browser (etc) settings in its canonical XML format.  Returns the default
16191     * browser XML representation as a byte array, or null if there is none.
16192     */
16193    @Override
16194    public byte[] getDefaultAppsBackup(int userId) {
16195        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16196            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16197        }
16198
16199        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16200        try {
16201            final XmlSerializer serializer = new FastXmlSerializer();
16202            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16203            serializer.startDocument(null, true);
16204            serializer.startTag(null, TAG_DEFAULT_APPS);
16205
16206            synchronized (mPackages) {
16207                mSettings.writeDefaultAppsLPr(serializer, userId);
16208            }
16209
16210            serializer.endTag(null, TAG_DEFAULT_APPS);
16211            serializer.endDocument();
16212            serializer.flush();
16213        } catch (Exception e) {
16214            if (DEBUG_BACKUP) {
16215                Slog.e(TAG, "Unable to write default apps for backup", e);
16216            }
16217            return null;
16218        }
16219
16220        return dataStream.toByteArray();
16221    }
16222
16223    @Override
16224    public void restoreDefaultApps(byte[] backup, int userId) {
16225        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16226            throw new SecurityException("Only the system may call restoreDefaultApps()");
16227        }
16228
16229        try {
16230            final XmlPullParser parser = Xml.newPullParser();
16231            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16232            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16233                    new BlobXmlRestorer() {
16234                        @Override
16235                        public void apply(XmlPullParser parser, int userId)
16236                                throws XmlPullParserException, IOException {
16237                            synchronized (mPackages) {
16238                                mSettings.readDefaultAppsLPw(parser, userId);
16239                            }
16240                        }
16241                    } );
16242        } catch (Exception e) {
16243            if (DEBUG_BACKUP) {
16244                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16245            }
16246        }
16247    }
16248
16249    @Override
16250    public byte[] getIntentFilterVerificationBackup(int userId) {
16251        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16252            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16253        }
16254
16255        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16256        try {
16257            final XmlSerializer serializer = new FastXmlSerializer();
16258            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16259            serializer.startDocument(null, true);
16260            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16261
16262            synchronized (mPackages) {
16263                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16264            }
16265
16266            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16267            serializer.endDocument();
16268            serializer.flush();
16269        } catch (Exception e) {
16270            if (DEBUG_BACKUP) {
16271                Slog.e(TAG, "Unable to write default apps for backup", e);
16272            }
16273            return null;
16274        }
16275
16276        return dataStream.toByteArray();
16277    }
16278
16279    @Override
16280    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16281        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16282            throw new SecurityException("Only the system may call restorePreferredActivities()");
16283        }
16284
16285        try {
16286            final XmlPullParser parser = Xml.newPullParser();
16287            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16288            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16289                    new BlobXmlRestorer() {
16290                        @Override
16291                        public void apply(XmlPullParser parser, int userId)
16292                                throws XmlPullParserException, IOException {
16293                            synchronized (mPackages) {
16294                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16295                                mSettings.writeLPr();
16296                            }
16297                        }
16298                    } );
16299        } catch (Exception e) {
16300            if (DEBUG_BACKUP) {
16301                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16302            }
16303        }
16304    }
16305
16306    @Override
16307    public byte[] getPermissionGrantBackup(int userId) {
16308        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16309            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16310        }
16311
16312        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16313        try {
16314            final XmlSerializer serializer = new FastXmlSerializer();
16315            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16316            serializer.startDocument(null, true);
16317            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16318
16319            synchronized (mPackages) {
16320                serializeRuntimePermissionGrantsLPr(serializer, userId);
16321            }
16322
16323            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16324            serializer.endDocument();
16325            serializer.flush();
16326        } catch (Exception e) {
16327            if (DEBUG_BACKUP) {
16328                Slog.e(TAG, "Unable to write default apps for backup", e);
16329            }
16330            return null;
16331        }
16332
16333        return dataStream.toByteArray();
16334    }
16335
16336    @Override
16337    public void restorePermissionGrants(byte[] backup, int userId) {
16338        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16339            throw new SecurityException("Only the system may call restorePermissionGrants()");
16340        }
16341
16342        try {
16343            final XmlPullParser parser = Xml.newPullParser();
16344            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16345            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16346                    new BlobXmlRestorer() {
16347                        @Override
16348                        public void apply(XmlPullParser parser, int userId)
16349                                throws XmlPullParserException, IOException {
16350                            synchronized (mPackages) {
16351                                processRestoredPermissionGrantsLPr(parser, userId);
16352                            }
16353                        }
16354                    } );
16355        } catch (Exception e) {
16356            if (DEBUG_BACKUP) {
16357                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16358            }
16359        }
16360    }
16361
16362    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16363            throws IOException {
16364        serializer.startTag(null, TAG_ALL_GRANTS);
16365
16366        final int N = mSettings.mPackages.size();
16367        for (int i = 0; i < N; i++) {
16368            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16369            boolean pkgGrantsKnown = false;
16370
16371            PermissionsState packagePerms = ps.getPermissionsState();
16372
16373            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16374                final int grantFlags = state.getFlags();
16375                // only look at grants that are not system/policy fixed
16376                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16377                    final boolean isGranted = state.isGranted();
16378                    // And only back up the user-twiddled state bits
16379                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16380                        final String packageName = mSettings.mPackages.keyAt(i);
16381                        if (!pkgGrantsKnown) {
16382                            serializer.startTag(null, TAG_GRANT);
16383                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16384                            pkgGrantsKnown = true;
16385                        }
16386
16387                        final boolean userSet =
16388                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16389                        final boolean userFixed =
16390                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16391                        final boolean revoke =
16392                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16393
16394                        serializer.startTag(null, TAG_PERMISSION);
16395                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16396                        if (isGranted) {
16397                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16398                        }
16399                        if (userSet) {
16400                            serializer.attribute(null, ATTR_USER_SET, "true");
16401                        }
16402                        if (userFixed) {
16403                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16404                        }
16405                        if (revoke) {
16406                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16407                        }
16408                        serializer.endTag(null, TAG_PERMISSION);
16409                    }
16410                }
16411            }
16412
16413            if (pkgGrantsKnown) {
16414                serializer.endTag(null, TAG_GRANT);
16415            }
16416        }
16417
16418        serializer.endTag(null, TAG_ALL_GRANTS);
16419    }
16420
16421    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16422            throws XmlPullParserException, IOException {
16423        String pkgName = null;
16424        int outerDepth = parser.getDepth();
16425        int type;
16426        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16427                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16428            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16429                continue;
16430            }
16431
16432            final String tagName = parser.getName();
16433            if (tagName.equals(TAG_GRANT)) {
16434                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16435                if (DEBUG_BACKUP) {
16436                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16437                }
16438            } else if (tagName.equals(TAG_PERMISSION)) {
16439
16440                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16441                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16442
16443                int newFlagSet = 0;
16444                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16445                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16446                }
16447                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16448                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16449                }
16450                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16451                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16452                }
16453                if (DEBUG_BACKUP) {
16454                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16455                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16456                }
16457                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16458                if (ps != null) {
16459                    // Already installed so we apply the grant immediately
16460                    if (DEBUG_BACKUP) {
16461                        Slog.v(TAG, "        + already installed; applying");
16462                    }
16463                    PermissionsState perms = ps.getPermissionsState();
16464                    BasePermission bp = mSettings.mPermissions.get(permName);
16465                    if (bp != null) {
16466                        if (isGranted) {
16467                            perms.grantRuntimePermission(bp, userId);
16468                        }
16469                        if (newFlagSet != 0) {
16470                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16471                        }
16472                    }
16473                } else {
16474                    // Need to wait for post-restore install to apply the grant
16475                    if (DEBUG_BACKUP) {
16476                        Slog.v(TAG, "        - not yet installed; saving for later");
16477                    }
16478                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16479                            isGranted, newFlagSet, userId);
16480                }
16481            } else {
16482                PackageManagerService.reportSettingsProblem(Log.WARN,
16483                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16484                XmlUtils.skipCurrentTag(parser);
16485            }
16486        }
16487
16488        scheduleWriteSettingsLocked();
16489        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16490    }
16491
16492    @Override
16493    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16494            int sourceUserId, int targetUserId, int flags) {
16495        mContext.enforceCallingOrSelfPermission(
16496                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16497        int callingUid = Binder.getCallingUid();
16498        enforceOwnerRights(ownerPackage, callingUid);
16499        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16500        if (intentFilter.countActions() == 0) {
16501            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16502            return;
16503        }
16504        synchronized (mPackages) {
16505            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16506                    ownerPackage, targetUserId, flags);
16507            CrossProfileIntentResolver resolver =
16508                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16509            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16510            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16511            if (existing != null) {
16512                int size = existing.size();
16513                for (int i = 0; i < size; i++) {
16514                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16515                        return;
16516                    }
16517                }
16518            }
16519            resolver.addFilter(newFilter);
16520            scheduleWritePackageRestrictionsLocked(sourceUserId);
16521        }
16522    }
16523
16524    @Override
16525    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16526        mContext.enforceCallingOrSelfPermission(
16527                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16528        int callingUid = Binder.getCallingUid();
16529        enforceOwnerRights(ownerPackage, callingUid);
16530        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16531        synchronized (mPackages) {
16532            CrossProfileIntentResolver resolver =
16533                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16534            ArraySet<CrossProfileIntentFilter> set =
16535                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16536            for (CrossProfileIntentFilter filter : set) {
16537                if (filter.getOwnerPackage().equals(ownerPackage)) {
16538                    resolver.removeFilter(filter);
16539                }
16540            }
16541            scheduleWritePackageRestrictionsLocked(sourceUserId);
16542        }
16543    }
16544
16545    // Enforcing that callingUid is owning pkg on userId
16546    private void enforceOwnerRights(String pkg, int callingUid) {
16547        // The system owns everything.
16548        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16549            return;
16550        }
16551        int callingUserId = UserHandle.getUserId(callingUid);
16552        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16553        if (pi == null) {
16554            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16555                    + callingUserId);
16556        }
16557        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16558            throw new SecurityException("Calling uid " + callingUid
16559                    + " does not own package " + pkg);
16560        }
16561    }
16562
16563    @Override
16564    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16565        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16566    }
16567
16568    private Intent getHomeIntent() {
16569        Intent intent = new Intent(Intent.ACTION_MAIN);
16570        intent.addCategory(Intent.CATEGORY_HOME);
16571        return intent;
16572    }
16573
16574    private IntentFilter getHomeFilter() {
16575        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16576        filter.addCategory(Intent.CATEGORY_HOME);
16577        filter.addCategory(Intent.CATEGORY_DEFAULT);
16578        return filter;
16579    }
16580
16581    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16582            int userId) {
16583        Intent intent  = getHomeIntent();
16584        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16585                PackageManager.GET_META_DATA, userId);
16586        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16587                true, false, false, userId);
16588
16589        allHomeCandidates.clear();
16590        if (list != null) {
16591            for (ResolveInfo ri : list) {
16592                allHomeCandidates.add(ri);
16593            }
16594        }
16595        return (preferred == null || preferred.activityInfo == null)
16596                ? null
16597                : new ComponentName(preferred.activityInfo.packageName,
16598                        preferred.activityInfo.name);
16599    }
16600
16601    @Override
16602    public void setHomeActivity(ComponentName comp, int userId) {
16603        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16604        getHomeActivitiesAsUser(homeActivities, userId);
16605
16606        boolean found = false;
16607
16608        final int size = homeActivities.size();
16609        final ComponentName[] set = new ComponentName[size];
16610        for (int i = 0; i < size; i++) {
16611            final ResolveInfo candidate = homeActivities.get(i);
16612            final ActivityInfo info = candidate.activityInfo;
16613            final ComponentName activityName = new ComponentName(info.packageName, info.name);
16614            set[i] = activityName;
16615            if (!found && activityName.equals(comp)) {
16616                found = true;
16617            }
16618        }
16619        if (!found) {
16620            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
16621                    + userId);
16622        }
16623        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
16624                set, comp, userId);
16625    }
16626
16627    @Override
16628    public void setApplicationEnabledSetting(String appPackageName,
16629            int newState, int flags, int userId, String callingPackage) {
16630        if (!sUserManager.exists(userId)) return;
16631        if (callingPackage == null) {
16632            callingPackage = Integer.toString(Binder.getCallingUid());
16633        }
16634        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16635    }
16636
16637    @Override
16638    public void setComponentEnabledSetting(ComponentName componentName,
16639            int newState, int flags, int userId) {
16640        if (!sUserManager.exists(userId)) return;
16641        setEnabledSetting(componentName.getPackageName(),
16642                componentName.getClassName(), newState, flags, userId, null);
16643    }
16644
16645    private void setEnabledSetting(final String packageName, String className, int newState,
16646            final int flags, int userId, String callingPackage) {
16647        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16648              || newState == COMPONENT_ENABLED_STATE_ENABLED
16649              || newState == COMPONENT_ENABLED_STATE_DISABLED
16650              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16651              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16652            throw new IllegalArgumentException("Invalid new component state: "
16653                    + newState);
16654        }
16655        PackageSetting pkgSetting;
16656        final int uid = Binder.getCallingUid();
16657        final int permission = mContext.checkCallingOrSelfPermission(
16658                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16659        enforceCrossUserPermission(uid, userId,
16660                false /* requireFullPermission */, true /* checkShell */, "set enabled");
16661        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16662        boolean sendNow = false;
16663        boolean isApp = (className == null);
16664        String componentName = isApp ? packageName : className;
16665        int packageUid = -1;
16666        ArrayList<String> components;
16667
16668        // writer
16669        synchronized (mPackages) {
16670            pkgSetting = mSettings.mPackages.get(packageName);
16671            if (pkgSetting == null) {
16672                if (className == null) {
16673                    throw new IllegalArgumentException("Unknown package: " + packageName);
16674                }
16675                throw new IllegalArgumentException(
16676                        "Unknown component: " + packageName + "/" + className);
16677            }
16678            // Allow root and verify that userId is not being specified by a different user
16679            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16680                throw new SecurityException(
16681                        "Permission Denial: attempt to change component state from pid="
16682                        + Binder.getCallingPid()
16683                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16684            }
16685            if (className == null) {
16686                // We're dealing with an application/package level state change
16687                if (pkgSetting.getEnabled(userId) == newState) {
16688                    // Nothing to do
16689                    return;
16690                }
16691                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16692                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16693                    // Don't care about who enables an app.
16694                    callingPackage = null;
16695                }
16696                pkgSetting.setEnabled(newState, userId, callingPackage);
16697                // pkgSetting.pkg.mSetEnabled = newState;
16698            } else {
16699                // We're dealing with a component level state change
16700                // First, verify that this is a valid class name.
16701                PackageParser.Package pkg = pkgSetting.pkg;
16702                if (pkg == null || !pkg.hasComponentClassName(className)) {
16703                    if (pkg != null &&
16704                            pkg.applicationInfo.targetSdkVersion >=
16705                                    Build.VERSION_CODES.JELLY_BEAN) {
16706                        throw new IllegalArgumentException("Component class " + className
16707                                + " does not exist in " + packageName);
16708                    } else {
16709                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16710                                + className + " does not exist in " + packageName);
16711                    }
16712                }
16713                switch (newState) {
16714                case COMPONENT_ENABLED_STATE_ENABLED:
16715                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16716                        return;
16717                    }
16718                    break;
16719                case COMPONENT_ENABLED_STATE_DISABLED:
16720                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16721                        return;
16722                    }
16723                    break;
16724                case COMPONENT_ENABLED_STATE_DEFAULT:
16725                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16726                        return;
16727                    }
16728                    break;
16729                default:
16730                    Slog.e(TAG, "Invalid new component state: " + newState);
16731                    return;
16732                }
16733            }
16734            scheduleWritePackageRestrictionsLocked(userId);
16735            components = mPendingBroadcasts.get(userId, packageName);
16736            final boolean newPackage = components == null;
16737            if (newPackage) {
16738                components = new ArrayList<String>();
16739            }
16740            if (!components.contains(componentName)) {
16741                components.add(componentName);
16742            }
16743            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16744                sendNow = true;
16745                // Purge entry from pending broadcast list if another one exists already
16746                // since we are sending one right away.
16747                mPendingBroadcasts.remove(userId, packageName);
16748            } else {
16749                if (newPackage) {
16750                    mPendingBroadcasts.put(userId, packageName, components);
16751                }
16752                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16753                    // Schedule a message
16754                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16755                }
16756            }
16757        }
16758
16759        long callingId = Binder.clearCallingIdentity();
16760        try {
16761            if (sendNow) {
16762                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16763                sendPackageChangedBroadcast(packageName,
16764                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16765            }
16766        } finally {
16767            Binder.restoreCallingIdentity(callingId);
16768        }
16769    }
16770
16771    @Override
16772    public void flushPackageRestrictionsAsUser(int userId) {
16773        if (!sUserManager.exists(userId)) {
16774            return;
16775        }
16776        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
16777                false /* checkShell */, "flushPackageRestrictions");
16778        synchronized (mPackages) {
16779            mSettings.writePackageRestrictionsLPr(userId);
16780            mDirtyUsers.remove(userId);
16781            if (mDirtyUsers.isEmpty()) {
16782                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
16783            }
16784        }
16785    }
16786
16787    private void sendPackageChangedBroadcast(String packageName,
16788            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16789        if (DEBUG_INSTALL)
16790            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16791                    + componentNames);
16792        Bundle extras = new Bundle(4);
16793        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16794        String nameList[] = new String[componentNames.size()];
16795        componentNames.toArray(nameList);
16796        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16797        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16798        extras.putInt(Intent.EXTRA_UID, packageUid);
16799        // If this is not reporting a change of the overall package, then only send it
16800        // to registered receivers.  We don't want to launch a swath of apps for every
16801        // little component state change.
16802        final int flags = !componentNames.contains(packageName)
16803                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16804        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16805                new int[] {UserHandle.getUserId(packageUid)});
16806    }
16807
16808    @Override
16809    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16810        if (!sUserManager.exists(userId)) return;
16811        final int uid = Binder.getCallingUid();
16812        final int permission = mContext.checkCallingOrSelfPermission(
16813                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16814        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16815        enforceCrossUserPermission(uid, userId,
16816                true /* requireFullPermission */, true /* checkShell */, "stop package");
16817        // writer
16818        synchronized (mPackages) {
16819            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16820                    allowedByPermission, uid, userId)) {
16821                scheduleWritePackageRestrictionsLocked(userId);
16822            }
16823        }
16824    }
16825
16826    @Override
16827    public String getInstallerPackageName(String packageName) {
16828        // reader
16829        synchronized (mPackages) {
16830            return mSettings.getInstallerPackageNameLPr(packageName);
16831        }
16832    }
16833
16834    @Override
16835    public int getApplicationEnabledSetting(String packageName, int userId) {
16836        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16837        int uid = Binder.getCallingUid();
16838        enforceCrossUserPermission(uid, userId,
16839                false /* requireFullPermission */, false /* checkShell */, "get enabled");
16840        // reader
16841        synchronized (mPackages) {
16842            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16843        }
16844    }
16845
16846    @Override
16847    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16848        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16849        int uid = Binder.getCallingUid();
16850        enforceCrossUserPermission(uid, userId,
16851                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
16852        // reader
16853        synchronized (mPackages) {
16854            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16855        }
16856    }
16857
16858    @Override
16859    public void enterSafeMode() {
16860        enforceSystemOrRoot("Only the system can request entering safe mode");
16861
16862        if (!mSystemReady) {
16863            mSafeMode = true;
16864        }
16865    }
16866
16867    @Override
16868    public void systemReady() {
16869        mSystemReady = true;
16870
16871        // Read the compatibilty setting when the system is ready.
16872        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16873                mContext.getContentResolver(),
16874                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16875        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16876        if (DEBUG_SETTINGS) {
16877            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16878        }
16879
16880        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16881
16882        synchronized (mPackages) {
16883            // Verify that all of the preferred activity components actually
16884            // exist.  It is possible for applications to be updated and at
16885            // that point remove a previously declared activity component that
16886            // had been set as a preferred activity.  We try to clean this up
16887            // the next time we encounter that preferred activity, but it is
16888            // possible for the user flow to never be able to return to that
16889            // situation so here we do a sanity check to make sure we haven't
16890            // left any junk around.
16891            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16892            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16893                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16894                removed.clear();
16895                for (PreferredActivity pa : pir.filterSet()) {
16896                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16897                        removed.add(pa);
16898                    }
16899                }
16900                if (removed.size() > 0) {
16901                    for (int r=0; r<removed.size(); r++) {
16902                        PreferredActivity pa = removed.get(r);
16903                        Slog.w(TAG, "Removing dangling preferred activity: "
16904                                + pa.mPref.mComponent);
16905                        pir.removeFilter(pa);
16906                    }
16907                    mSettings.writePackageRestrictionsLPr(
16908                            mSettings.mPreferredActivities.keyAt(i));
16909                }
16910            }
16911
16912            for (int userId : UserManagerService.getInstance().getUserIds()) {
16913                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16914                    grantPermissionsUserIds = ArrayUtils.appendInt(
16915                            grantPermissionsUserIds, userId);
16916                }
16917            }
16918        }
16919        sUserManager.systemReady();
16920
16921        // If we upgraded grant all default permissions before kicking off.
16922        for (int userId : grantPermissionsUserIds) {
16923            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16924        }
16925
16926        // Kick off any messages waiting for system ready
16927        if (mPostSystemReadyMessages != null) {
16928            for (Message msg : mPostSystemReadyMessages) {
16929                msg.sendToTarget();
16930            }
16931            mPostSystemReadyMessages = null;
16932        }
16933
16934        // Watch for external volumes that come and go over time
16935        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16936        storage.registerListener(mStorageListener);
16937
16938        mInstallerService.systemReady();
16939        mPackageDexOptimizer.systemReady();
16940
16941        MountServiceInternal mountServiceInternal = LocalServices.getService(
16942                MountServiceInternal.class);
16943        mountServiceInternal.addExternalStoragePolicy(
16944                new MountServiceInternal.ExternalStorageMountPolicy() {
16945            @Override
16946            public int getMountMode(int uid, String packageName) {
16947                if (Process.isIsolated(uid)) {
16948                    return Zygote.MOUNT_EXTERNAL_NONE;
16949                }
16950                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16951                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16952                }
16953                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16954                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16955                }
16956                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16957                    return Zygote.MOUNT_EXTERNAL_READ;
16958                }
16959                return Zygote.MOUNT_EXTERNAL_WRITE;
16960            }
16961
16962            @Override
16963            public boolean hasExternalStorage(int uid, String packageName) {
16964                return true;
16965            }
16966        });
16967    }
16968
16969    @Override
16970    public boolean isSafeMode() {
16971        return mSafeMode;
16972    }
16973
16974    @Override
16975    public boolean hasSystemUidErrors() {
16976        return mHasSystemUidErrors;
16977    }
16978
16979    static String arrayToString(int[] array) {
16980        StringBuffer buf = new StringBuffer(128);
16981        buf.append('[');
16982        if (array != null) {
16983            for (int i=0; i<array.length; i++) {
16984                if (i > 0) buf.append(", ");
16985                buf.append(array[i]);
16986            }
16987        }
16988        buf.append(']');
16989        return buf.toString();
16990    }
16991
16992    static class DumpState {
16993        public static final int DUMP_LIBS = 1 << 0;
16994        public static final int DUMP_FEATURES = 1 << 1;
16995        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16996        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16997        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16998        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16999        public static final int DUMP_PERMISSIONS = 1 << 6;
17000        public static final int DUMP_PACKAGES = 1 << 7;
17001        public static final int DUMP_SHARED_USERS = 1 << 8;
17002        public static final int DUMP_MESSAGES = 1 << 9;
17003        public static final int DUMP_PROVIDERS = 1 << 10;
17004        public static final int DUMP_VERIFIERS = 1 << 11;
17005        public static final int DUMP_PREFERRED = 1 << 12;
17006        public static final int DUMP_PREFERRED_XML = 1 << 13;
17007        public static final int DUMP_KEYSETS = 1 << 14;
17008        public static final int DUMP_VERSION = 1 << 15;
17009        public static final int DUMP_INSTALLS = 1 << 16;
17010        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17011        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17012
17013        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17014
17015        private int mTypes;
17016
17017        private int mOptions;
17018
17019        private boolean mTitlePrinted;
17020
17021        private SharedUserSetting mSharedUser;
17022
17023        public boolean isDumping(int type) {
17024            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17025                return true;
17026            }
17027
17028            return (mTypes & type) != 0;
17029        }
17030
17031        public void setDump(int type) {
17032            mTypes |= type;
17033        }
17034
17035        public boolean isOptionEnabled(int option) {
17036            return (mOptions & option) != 0;
17037        }
17038
17039        public void setOptionEnabled(int option) {
17040            mOptions |= option;
17041        }
17042
17043        public boolean onTitlePrinted() {
17044            final boolean printed = mTitlePrinted;
17045            mTitlePrinted = true;
17046            return printed;
17047        }
17048
17049        public boolean getTitlePrinted() {
17050            return mTitlePrinted;
17051        }
17052
17053        public void setTitlePrinted(boolean enabled) {
17054            mTitlePrinted = enabled;
17055        }
17056
17057        public SharedUserSetting getSharedUser() {
17058            return mSharedUser;
17059        }
17060
17061        public void setSharedUser(SharedUserSetting user) {
17062            mSharedUser = user;
17063        }
17064    }
17065
17066    @Override
17067    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17068            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17069        (new PackageManagerShellCommand(this)).exec(
17070                this, in, out, err, args, resultReceiver);
17071    }
17072
17073    @Override
17074    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17075        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17076                != PackageManager.PERMISSION_GRANTED) {
17077            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17078                    + Binder.getCallingPid()
17079                    + ", uid=" + Binder.getCallingUid()
17080                    + " without permission "
17081                    + android.Manifest.permission.DUMP);
17082            return;
17083        }
17084
17085        DumpState dumpState = new DumpState();
17086        boolean fullPreferred = false;
17087        boolean checkin = false;
17088
17089        String packageName = null;
17090        ArraySet<String> permissionNames = null;
17091
17092        int opti = 0;
17093        while (opti < args.length) {
17094            String opt = args[opti];
17095            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17096                break;
17097            }
17098            opti++;
17099
17100            if ("-a".equals(opt)) {
17101                // Right now we only know how to print all.
17102            } else if ("-h".equals(opt)) {
17103                pw.println("Package manager dump options:");
17104                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17105                pw.println("    --checkin: dump for a checkin");
17106                pw.println("    -f: print details of intent filters");
17107                pw.println("    -h: print this help");
17108                pw.println("  cmd may be one of:");
17109                pw.println("    l[ibraries]: list known shared libraries");
17110                pw.println("    f[eatures]: list device features");
17111                pw.println("    k[eysets]: print known keysets");
17112                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17113                pw.println("    perm[issions]: dump permissions");
17114                pw.println("    permission [name ...]: dump declaration and use of given permission");
17115                pw.println("    pref[erred]: print preferred package settings");
17116                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17117                pw.println("    prov[iders]: dump content providers");
17118                pw.println("    p[ackages]: dump installed packages");
17119                pw.println("    s[hared-users]: dump shared user IDs");
17120                pw.println("    m[essages]: print collected runtime messages");
17121                pw.println("    v[erifiers]: print package verifier info");
17122                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17123                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17124                pw.println("    version: print database version info");
17125                pw.println("    write: write current settings now");
17126                pw.println("    installs: details about install sessions");
17127                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17128                pw.println("    <package.name>: info about given package");
17129                return;
17130            } else if ("--checkin".equals(opt)) {
17131                checkin = true;
17132            } else if ("-f".equals(opt)) {
17133                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17134            } else {
17135                pw.println("Unknown argument: " + opt + "; use -h for help");
17136            }
17137        }
17138
17139        // Is the caller requesting to dump a particular piece of data?
17140        if (opti < args.length) {
17141            String cmd = args[opti];
17142            opti++;
17143            // Is this a package name?
17144            if ("android".equals(cmd) || cmd.contains(".")) {
17145                packageName = cmd;
17146                // When dumping a single package, we always dump all of its
17147                // filter information since the amount of data will be reasonable.
17148                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17149            } else if ("check-permission".equals(cmd)) {
17150                if (opti >= args.length) {
17151                    pw.println("Error: check-permission missing permission argument");
17152                    return;
17153                }
17154                String perm = args[opti];
17155                opti++;
17156                if (opti >= args.length) {
17157                    pw.println("Error: check-permission missing package argument");
17158                    return;
17159                }
17160                String pkg = args[opti];
17161                opti++;
17162                int user = UserHandle.getUserId(Binder.getCallingUid());
17163                if (opti < args.length) {
17164                    try {
17165                        user = Integer.parseInt(args[opti]);
17166                    } catch (NumberFormatException e) {
17167                        pw.println("Error: check-permission user argument is not a number: "
17168                                + args[opti]);
17169                        return;
17170                    }
17171                }
17172                pw.println(checkPermission(perm, pkg, user));
17173                return;
17174            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17175                dumpState.setDump(DumpState.DUMP_LIBS);
17176            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17177                dumpState.setDump(DumpState.DUMP_FEATURES);
17178            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17179                if (opti >= args.length) {
17180                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17181                            | DumpState.DUMP_SERVICE_RESOLVERS
17182                            | DumpState.DUMP_RECEIVER_RESOLVERS
17183                            | DumpState.DUMP_CONTENT_RESOLVERS);
17184                } else {
17185                    while (opti < args.length) {
17186                        String name = args[opti];
17187                        if ("a".equals(name) || "activity".equals(name)) {
17188                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17189                        } else if ("s".equals(name) || "service".equals(name)) {
17190                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17191                        } else if ("r".equals(name) || "receiver".equals(name)) {
17192                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17193                        } else if ("c".equals(name) || "content".equals(name)) {
17194                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17195                        } else {
17196                            pw.println("Error: unknown resolver table type: " + name);
17197                            return;
17198                        }
17199                        opti++;
17200                    }
17201                }
17202            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17203                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17204            } else if ("permission".equals(cmd)) {
17205                if (opti >= args.length) {
17206                    pw.println("Error: permission requires permission name");
17207                    return;
17208                }
17209                permissionNames = new ArraySet<>();
17210                while (opti < args.length) {
17211                    permissionNames.add(args[opti]);
17212                    opti++;
17213                }
17214                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17215                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17216            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17217                dumpState.setDump(DumpState.DUMP_PREFERRED);
17218            } else if ("preferred-xml".equals(cmd)) {
17219                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17220                if (opti < args.length && "--full".equals(args[opti])) {
17221                    fullPreferred = true;
17222                    opti++;
17223                }
17224            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17225                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17226            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17227                dumpState.setDump(DumpState.DUMP_PACKAGES);
17228            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17229                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17230            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17231                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17232            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17233                dumpState.setDump(DumpState.DUMP_MESSAGES);
17234            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17235                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17236            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17237                    || "intent-filter-verifiers".equals(cmd)) {
17238                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17239            } else if ("version".equals(cmd)) {
17240                dumpState.setDump(DumpState.DUMP_VERSION);
17241            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17242                dumpState.setDump(DumpState.DUMP_KEYSETS);
17243            } else if ("installs".equals(cmd)) {
17244                dumpState.setDump(DumpState.DUMP_INSTALLS);
17245            } else if ("write".equals(cmd)) {
17246                synchronized (mPackages) {
17247                    mSettings.writeLPr();
17248                    pw.println("Settings written.");
17249                    return;
17250                }
17251            }
17252        }
17253
17254        if (checkin) {
17255            pw.println("vers,1");
17256        }
17257
17258        // reader
17259        synchronized (mPackages) {
17260            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17261                if (!checkin) {
17262                    if (dumpState.onTitlePrinted())
17263                        pw.println();
17264                    pw.println("Database versions:");
17265                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17266                }
17267            }
17268
17269            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17270                if (!checkin) {
17271                    if (dumpState.onTitlePrinted())
17272                        pw.println();
17273                    pw.println("Verifiers:");
17274                    pw.print("  Required: ");
17275                    pw.print(mRequiredVerifierPackage);
17276                    pw.print(" (uid=");
17277                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17278                            UserHandle.USER_SYSTEM));
17279                    pw.println(")");
17280                } else if (mRequiredVerifierPackage != null) {
17281                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17282                    pw.print(",");
17283                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17284                            UserHandle.USER_SYSTEM));
17285                }
17286            }
17287
17288            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17289                    packageName == null) {
17290                if (mIntentFilterVerifierComponent != null) {
17291                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17292                    if (!checkin) {
17293                        if (dumpState.onTitlePrinted())
17294                            pw.println();
17295                        pw.println("Intent Filter Verifier:");
17296                        pw.print("  Using: ");
17297                        pw.print(verifierPackageName);
17298                        pw.print(" (uid=");
17299                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17300                                UserHandle.USER_SYSTEM));
17301                        pw.println(")");
17302                    } else if (verifierPackageName != null) {
17303                        pw.print("ifv,"); pw.print(verifierPackageName);
17304                        pw.print(",");
17305                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17306                                UserHandle.USER_SYSTEM));
17307                    }
17308                } else {
17309                    pw.println();
17310                    pw.println("No Intent Filter Verifier available!");
17311                }
17312            }
17313
17314            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17315                boolean printedHeader = false;
17316                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17317                while (it.hasNext()) {
17318                    String name = it.next();
17319                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17320                    if (!checkin) {
17321                        if (!printedHeader) {
17322                            if (dumpState.onTitlePrinted())
17323                                pw.println();
17324                            pw.println("Libraries:");
17325                            printedHeader = true;
17326                        }
17327                        pw.print("  ");
17328                    } else {
17329                        pw.print("lib,");
17330                    }
17331                    pw.print(name);
17332                    if (!checkin) {
17333                        pw.print(" -> ");
17334                    }
17335                    if (ent.path != null) {
17336                        if (!checkin) {
17337                            pw.print("(jar) ");
17338                            pw.print(ent.path);
17339                        } else {
17340                            pw.print(",jar,");
17341                            pw.print(ent.path);
17342                        }
17343                    } else {
17344                        if (!checkin) {
17345                            pw.print("(apk) ");
17346                            pw.print(ent.apk);
17347                        } else {
17348                            pw.print(",apk,");
17349                            pw.print(ent.apk);
17350                        }
17351                    }
17352                    pw.println();
17353                }
17354            }
17355
17356            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17357                if (dumpState.onTitlePrinted())
17358                    pw.println();
17359                if (!checkin) {
17360                    pw.println("Features:");
17361                }
17362
17363                for (FeatureInfo feat : mAvailableFeatures.values()) {
17364                    if (checkin) {
17365                        pw.print("feat,");
17366                        pw.print(feat.name);
17367                        pw.print(",");
17368                        pw.println(feat.version);
17369                    } else {
17370                        pw.print("  ");
17371                        pw.print(feat.name);
17372                        if (feat.version > 0) {
17373                            pw.print(" version=");
17374                            pw.print(feat.version);
17375                        }
17376                        pw.println();
17377                    }
17378                }
17379            }
17380
17381            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17382                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17383                        : "Activity Resolver Table:", "  ", packageName,
17384                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17385                    dumpState.setTitlePrinted(true);
17386                }
17387            }
17388            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17389                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17390                        : "Receiver Resolver Table:", "  ", packageName,
17391                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17392                    dumpState.setTitlePrinted(true);
17393                }
17394            }
17395            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17396                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17397                        : "Service Resolver Table:", "  ", packageName,
17398                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17399                    dumpState.setTitlePrinted(true);
17400                }
17401            }
17402            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17403                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17404                        : "Provider Resolver Table:", "  ", packageName,
17405                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17406                    dumpState.setTitlePrinted(true);
17407                }
17408            }
17409
17410            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17411                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17412                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17413                    int user = mSettings.mPreferredActivities.keyAt(i);
17414                    if (pir.dump(pw,
17415                            dumpState.getTitlePrinted()
17416                                ? "\nPreferred Activities User " + user + ":"
17417                                : "Preferred Activities User " + user + ":", "  ",
17418                            packageName, true, false)) {
17419                        dumpState.setTitlePrinted(true);
17420                    }
17421                }
17422            }
17423
17424            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17425                pw.flush();
17426                FileOutputStream fout = new FileOutputStream(fd);
17427                BufferedOutputStream str = new BufferedOutputStream(fout);
17428                XmlSerializer serializer = new FastXmlSerializer();
17429                try {
17430                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17431                    serializer.startDocument(null, true);
17432                    serializer.setFeature(
17433                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17434                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17435                    serializer.endDocument();
17436                    serializer.flush();
17437                } catch (IllegalArgumentException e) {
17438                    pw.println("Failed writing: " + e);
17439                } catch (IllegalStateException e) {
17440                    pw.println("Failed writing: " + e);
17441                } catch (IOException e) {
17442                    pw.println("Failed writing: " + e);
17443                }
17444            }
17445
17446            if (!checkin
17447                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17448                    && packageName == null) {
17449                pw.println();
17450                int count = mSettings.mPackages.size();
17451                if (count == 0) {
17452                    pw.println("No applications!");
17453                    pw.println();
17454                } else {
17455                    final String prefix = "  ";
17456                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17457                    if (allPackageSettings.size() == 0) {
17458                        pw.println("No domain preferred apps!");
17459                        pw.println();
17460                    } else {
17461                        pw.println("App verification status:");
17462                        pw.println();
17463                        count = 0;
17464                        for (PackageSetting ps : allPackageSettings) {
17465                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17466                            if (ivi == null || ivi.getPackageName() == null) continue;
17467                            pw.println(prefix + "Package: " + ivi.getPackageName());
17468                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17469                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17470                            pw.println();
17471                            count++;
17472                        }
17473                        if (count == 0) {
17474                            pw.println(prefix + "No app verification established.");
17475                            pw.println();
17476                        }
17477                        for (int userId : sUserManager.getUserIds()) {
17478                            pw.println("App linkages for user " + userId + ":");
17479                            pw.println();
17480                            count = 0;
17481                            for (PackageSetting ps : allPackageSettings) {
17482                                final long status = ps.getDomainVerificationStatusForUser(userId);
17483                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17484                                    continue;
17485                                }
17486                                pw.println(prefix + "Package: " + ps.name);
17487                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17488                                String statusStr = IntentFilterVerificationInfo.
17489                                        getStatusStringFromValue(status);
17490                                pw.println(prefix + "Status:  " + statusStr);
17491                                pw.println();
17492                                count++;
17493                            }
17494                            if (count == 0) {
17495                                pw.println(prefix + "No configured app linkages.");
17496                                pw.println();
17497                            }
17498                        }
17499                    }
17500                }
17501            }
17502
17503            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17504                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17505                if (packageName == null && permissionNames == null) {
17506                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17507                        if (iperm == 0) {
17508                            if (dumpState.onTitlePrinted())
17509                                pw.println();
17510                            pw.println("AppOp Permissions:");
17511                        }
17512                        pw.print("  AppOp Permission ");
17513                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17514                        pw.println(":");
17515                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17516                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17517                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17518                        }
17519                    }
17520                }
17521            }
17522
17523            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17524                boolean printedSomething = false;
17525                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17526                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17527                        continue;
17528                    }
17529                    if (!printedSomething) {
17530                        if (dumpState.onTitlePrinted())
17531                            pw.println();
17532                        pw.println("Registered ContentProviders:");
17533                        printedSomething = true;
17534                    }
17535                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17536                    pw.print("    "); pw.println(p.toString());
17537                }
17538                printedSomething = false;
17539                for (Map.Entry<String, PackageParser.Provider> entry :
17540                        mProvidersByAuthority.entrySet()) {
17541                    PackageParser.Provider p = entry.getValue();
17542                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17543                        continue;
17544                    }
17545                    if (!printedSomething) {
17546                        if (dumpState.onTitlePrinted())
17547                            pw.println();
17548                        pw.println("ContentProvider Authorities:");
17549                        printedSomething = true;
17550                    }
17551                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17552                    pw.print("    "); pw.println(p.toString());
17553                    if (p.info != null && p.info.applicationInfo != null) {
17554                        final String appInfo = p.info.applicationInfo.toString();
17555                        pw.print("      applicationInfo="); pw.println(appInfo);
17556                    }
17557                }
17558            }
17559
17560            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17561                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17562            }
17563
17564            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17565                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17566            }
17567
17568            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17569                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17570            }
17571
17572            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17573                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17574            }
17575
17576            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17577                // XXX should handle packageName != null by dumping only install data that
17578                // the given package is involved with.
17579                if (dumpState.onTitlePrinted()) pw.println();
17580                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17581            }
17582
17583            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17584                if (dumpState.onTitlePrinted()) pw.println();
17585                mSettings.dumpReadMessagesLPr(pw, dumpState);
17586
17587                pw.println();
17588                pw.println("Package warning messages:");
17589                BufferedReader in = null;
17590                String line = null;
17591                try {
17592                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17593                    while ((line = in.readLine()) != null) {
17594                        if (line.contains("ignored: updated version")) continue;
17595                        pw.println(line);
17596                    }
17597                } catch (IOException ignored) {
17598                } finally {
17599                    IoUtils.closeQuietly(in);
17600                }
17601            }
17602
17603            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17604                BufferedReader in = null;
17605                String line = null;
17606                try {
17607                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17608                    while ((line = in.readLine()) != null) {
17609                        if (line.contains("ignored: updated version")) continue;
17610                        pw.print("msg,");
17611                        pw.println(line);
17612                    }
17613                } catch (IOException ignored) {
17614                } finally {
17615                    IoUtils.closeQuietly(in);
17616                }
17617            }
17618        }
17619    }
17620
17621    private String dumpDomainString(String packageName) {
17622        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
17623                .getList();
17624        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
17625
17626        ArraySet<String> result = new ArraySet<>();
17627        if (iviList.size() > 0) {
17628            for (IntentFilterVerificationInfo ivi : iviList) {
17629                for (String host : ivi.getDomains()) {
17630                    result.add(host);
17631                }
17632            }
17633        }
17634        if (filters != null && filters.size() > 0) {
17635            for (IntentFilter filter : filters) {
17636                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17637                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17638                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17639                    result.addAll(filter.getHostsList());
17640                }
17641            }
17642        }
17643
17644        StringBuilder sb = new StringBuilder(result.size() * 16);
17645        for (String domain : result) {
17646            if (sb.length() > 0) sb.append(" ");
17647            sb.append(domain);
17648        }
17649        return sb.toString();
17650    }
17651
17652    // ------- apps on sdcard specific code -------
17653    static final boolean DEBUG_SD_INSTALL = false;
17654
17655    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17656
17657    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17658
17659    private boolean mMediaMounted = false;
17660
17661    static String getEncryptKey() {
17662        try {
17663            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17664                    SD_ENCRYPTION_KEYSTORE_NAME);
17665            if (sdEncKey == null) {
17666                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17667                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17668                if (sdEncKey == null) {
17669                    Slog.e(TAG, "Failed to create encryption keys");
17670                    return null;
17671                }
17672            }
17673            return sdEncKey;
17674        } catch (NoSuchAlgorithmException nsae) {
17675            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17676            return null;
17677        } catch (IOException ioe) {
17678            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17679            return null;
17680        }
17681    }
17682
17683    /*
17684     * Update media status on PackageManager.
17685     */
17686    @Override
17687    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17688        int callingUid = Binder.getCallingUid();
17689        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17690            throw new SecurityException("Media status can only be updated by the system");
17691        }
17692        // reader; this apparently protects mMediaMounted, but should probably
17693        // be a different lock in that case.
17694        synchronized (mPackages) {
17695            Log.i(TAG, "Updating external media status from "
17696                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17697                    + (mediaStatus ? "mounted" : "unmounted"));
17698            if (DEBUG_SD_INSTALL)
17699                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17700                        + ", mMediaMounted=" + mMediaMounted);
17701            if (mediaStatus == mMediaMounted) {
17702                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17703                        : 0, -1);
17704                mHandler.sendMessage(msg);
17705                return;
17706            }
17707            mMediaMounted = mediaStatus;
17708        }
17709        // Queue up an async operation since the package installation may take a
17710        // little while.
17711        mHandler.post(new Runnable() {
17712            public void run() {
17713                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17714            }
17715        });
17716    }
17717
17718    /**
17719     * Called by MountService when the initial ASECs to scan are available.
17720     * Should block until all the ASEC containers are finished being scanned.
17721     */
17722    public void scanAvailableAsecs() {
17723        updateExternalMediaStatusInner(true, false, false);
17724    }
17725
17726    /*
17727     * Collect information of applications on external media, map them against
17728     * existing containers and update information based on current mount status.
17729     * Please note that we always have to report status if reportStatus has been
17730     * set to true especially when unloading packages.
17731     */
17732    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17733            boolean externalStorage) {
17734        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17735        int[] uidArr = EmptyArray.INT;
17736
17737        final String[] list = PackageHelper.getSecureContainerList();
17738        if (ArrayUtils.isEmpty(list)) {
17739            Log.i(TAG, "No secure containers found");
17740        } else {
17741            // Process list of secure containers and categorize them
17742            // as active or stale based on their package internal state.
17743
17744            // reader
17745            synchronized (mPackages) {
17746                for (String cid : list) {
17747                    // Leave stages untouched for now; installer service owns them
17748                    if (PackageInstallerService.isStageName(cid)) continue;
17749
17750                    if (DEBUG_SD_INSTALL)
17751                        Log.i(TAG, "Processing container " + cid);
17752                    String pkgName = getAsecPackageName(cid);
17753                    if (pkgName == null) {
17754                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17755                        continue;
17756                    }
17757                    if (DEBUG_SD_INSTALL)
17758                        Log.i(TAG, "Looking for pkg : " + pkgName);
17759
17760                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17761                    if (ps == null) {
17762                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17763                        continue;
17764                    }
17765
17766                    /*
17767                     * Skip packages that are not external if we're unmounting
17768                     * external storage.
17769                     */
17770                    if (externalStorage && !isMounted && !isExternal(ps)) {
17771                        continue;
17772                    }
17773
17774                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17775                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17776                    // The package status is changed only if the code path
17777                    // matches between settings and the container id.
17778                    if (ps.codePathString != null
17779                            && ps.codePathString.startsWith(args.getCodePath())) {
17780                        if (DEBUG_SD_INSTALL) {
17781                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17782                                    + " at code path: " + ps.codePathString);
17783                        }
17784
17785                        // We do have a valid package installed on sdcard
17786                        processCids.put(args, ps.codePathString);
17787                        final int uid = ps.appId;
17788                        if (uid != -1) {
17789                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17790                        }
17791                    } else {
17792                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17793                                + ps.codePathString);
17794                    }
17795                }
17796            }
17797
17798            Arrays.sort(uidArr);
17799        }
17800
17801        // Process packages with valid entries.
17802        if (isMounted) {
17803            if (DEBUG_SD_INSTALL)
17804                Log.i(TAG, "Loading packages");
17805            loadMediaPackages(processCids, uidArr, externalStorage);
17806            startCleaningPackages();
17807            mInstallerService.onSecureContainersAvailable();
17808        } else {
17809            if (DEBUG_SD_INSTALL)
17810                Log.i(TAG, "Unloading packages");
17811            unloadMediaPackages(processCids, uidArr, reportStatus);
17812        }
17813    }
17814
17815    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17816            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17817        final int size = infos.size();
17818        final String[] packageNames = new String[size];
17819        final int[] packageUids = new int[size];
17820        for (int i = 0; i < size; i++) {
17821            final ApplicationInfo info = infos.get(i);
17822            packageNames[i] = info.packageName;
17823            packageUids[i] = info.uid;
17824        }
17825        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17826                finishedReceiver);
17827    }
17828
17829    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17830            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17831        sendResourcesChangedBroadcast(mediaStatus, replacing,
17832                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17833    }
17834
17835    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17836            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17837        int size = pkgList.length;
17838        if (size > 0) {
17839            // Send broadcasts here
17840            Bundle extras = new Bundle();
17841            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17842            if (uidArr != null) {
17843                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17844            }
17845            if (replacing) {
17846                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17847            }
17848            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17849                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17850            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17851        }
17852    }
17853
17854   /*
17855     * Look at potentially valid container ids from processCids If package
17856     * information doesn't match the one on record or package scanning fails,
17857     * the cid is added to list of removeCids. We currently don't delete stale
17858     * containers.
17859     */
17860    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17861            boolean externalStorage) {
17862        ArrayList<String> pkgList = new ArrayList<String>();
17863        Set<AsecInstallArgs> keys = processCids.keySet();
17864
17865        for (AsecInstallArgs args : keys) {
17866            String codePath = processCids.get(args);
17867            if (DEBUG_SD_INSTALL)
17868                Log.i(TAG, "Loading container : " + args.cid);
17869            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17870            try {
17871                // Make sure there are no container errors first.
17872                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17873                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17874                            + " when installing from sdcard");
17875                    continue;
17876                }
17877                // Check code path here.
17878                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17879                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17880                            + " does not match one in settings " + codePath);
17881                    continue;
17882                }
17883                // Parse package
17884                int parseFlags = mDefParseFlags;
17885                if (args.isExternalAsec()) {
17886                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17887                }
17888                if (args.isFwdLocked()) {
17889                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17890                }
17891
17892                synchronized (mInstallLock) {
17893                    PackageParser.Package pkg = null;
17894                    try {
17895                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17896                    } catch (PackageManagerException e) {
17897                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17898                    }
17899                    // Scan the package
17900                    if (pkg != null) {
17901                        /*
17902                         * TODO why is the lock being held? doPostInstall is
17903                         * called in other places without the lock. This needs
17904                         * to be straightened out.
17905                         */
17906                        // writer
17907                        synchronized (mPackages) {
17908                            retCode = PackageManager.INSTALL_SUCCEEDED;
17909                            pkgList.add(pkg.packageName);
17910                            // Post process args
17911                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17912                                    pkg.applicationInfo.uid);
17913                        }
17914                    } else {
17915                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17916                    }
17917                }
17918
17919            } finally {
17920                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17921                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17922                }
17923            }
17924        }
17925        // writer
17926        synchronized (mPackages) {
17927            // If the platform SDK has changed since the last time we booted,
17928            // we need to re-grant app permission to catch any new ones that
17929            // appear. This is really a hack, and means that apps can in some
17930            // cases get permissions that the user didn't initially explicitly
17931            // allow... it would be nice to have some better way to handle
17932            // this situation.
17933            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17934                    : mSettings.getInternalVersion();
17935            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17936                    : StorageManager.UUID_PRIVATE_INTERNAL;
17937
17938            int updateFlags = UPDATE_PERMISSIONS_ALL;
17939            if (ver.sdkVersion != mSdkVersion) {
17940                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17941                        + mSdkVersion + "; regranting permissions for external");
17942                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17943            }
17944            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17945
17946            // Yay, everything is now upgraded
17947            ver.forceCurrent();
17948
17949            // can downgrade to reader
17950            // Persist settings
17951            mSettings.writeLPr();
17952        }
17953        // Send a broadcast to let everyone know we are done processing
17954        if (pkgList.size() > 0) {
17955            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17956        }
17957    }
17958
17959   /*
17960     * Utility method to unload a list of specified containers
17961     */
17962    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17963        // Just unmount all valid containers.
17964        for (AsecInstallArgs arg : cidArgs) {
17965            synchronized (mInstallLock) {
17966                arg.doPostDeleteLI(false);
17967           }
17968       }
17969   }
17970
17971    /*
17972     * Unload packages mounted on external media. This involves deleting package
17973     * data from internal structures, sending broadcasts about disabled packages,
17974     * gc'ing to free up references, unmounting all secure containers
17975     * corresponding to packages on external media, and posting a
17976     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17977     * that we always have to post this message if status has been requested no
17978     * matter what.
17979     */
17980    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17981            final boolean reportStatus) {
17982        if (DEBUG_SD_INSTALL)
17983            Log.i(TAG, "unloading media packages");
17984        ArrayList<String> pkgList = new ArrayList<String>();
17985        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17986        final Set<AsecInstallArgs> keys = processCids.keySet();
17987        for (AsecInstallArgs args : keys) {
17988            String pkgName = args.getPackageName();
17989            if (DEBUG_SD_INSTALL)
17990                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17991            // Delete package internally
17992            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17993            synchronized (mInstallLock) {
17994                boolean res = deletePackageLI(pkgName, null, false, null,
17995                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17996                if (res) {
17997                    pkgList.add(pkgName);
17998                } else {
17999                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18000                    failedList.add(args);
18001                }
18002            }
18003        }
18004
18005        // reader
18006        synchronized (mPackages) {
18007            // We didn't update the settings after removing each package;
18008            // write them now for all packages.
18009            mSettings.writeLPr();
18010        }
18011
18012        // We have to absolutely send UPDATED_MEDIA_STATUS only
18013        // after confirming that all the receivers processed the ordered
18014        // broadcast when packages get disabled, force a gc to clean things up.
18015        // and unload all the containers.
18016        if (pkgList.size() > 0) {
18017            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18018                    new IIntentReceiver.Stub() {
18019                public void performReceive(Intent intent, int resultCode, String data,
18020                        Bundle extras, boolean ordered, boolean sticky,
18021                        int sendingUser) throws RemoteException {
18022                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18023                            reportStatus ? 1 : 0, 1, keys);
18024                    mHandler.sendMessage(msg);
18025                }
18026            });
18027        } else {
18028            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18029                    keys);
18030            mHandler.sendMessage(msg);
18031        }
18032    }
18033
18034    private void loadPrivatePackages(final VolumeInfo vol) {
18035        mHandler.post(new Runnable() {
18036            @Override
18037            public void run() {
18038                loadPrivatePackagesInner(vol);
18039            }
18040        });
18041    }
18042
18043    private void loadPrivatePackagesInner(VolumeInfo vol) {
18044        final String volumeUuid = vol.fsUuid;
18045        if (TextUtils.isEmpty(volumeUuid)) {
18046            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18047            return;
18048        }
18049
18050        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18051        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18052
18053        final VersionInfo ver;
18054        final List<PackageSetting> packages;
18055        synchronized (mPackages) {
18056            ver = mSettings.findOrCreateVersion(volumeUuid);
18057            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18058        }
18059
18060        // TODO: introduce a new concept similar to "frozen" to prevent these
18061        // apps from being launched until after data has been fully reconciled
18062        for (PackageSetting ps : packages) {
18063            synchronized (mInstallLock) {
18064                final PackageParser.Package pkg;
18065                try {
18066                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18067                    loaded.add(pkg.applicationInfo);
18068
18069                } catch (PackageManagerException e) {
18070                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18071                }
18072
18073                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18074                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
18075                }
18076            }
18077        }
18078
18079        // Reconcile app data for all started/unlocked users
18080        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18081        final UserManager um = mContext.getSystemService(UserManager.class);
18082        for (UserInfo user : um.getUsers()) {
18083            final int flags;
18084            if (um.isUserUnlocked(user.id)) {
18085                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18086            } else if (um.isUserRunning(user.id)) {
18087                flags = StorageManager.FLAG_STORAGE_DE;
18088            } else {
18089                continue;
18090            }
18091
18092            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18093            reconcileAppsData(volumeUuid, user.id, flags);
18094        }
18095
18096        synchronized (mPackages) {
18097            int updateFlags = UPDATE_PERMISSIONS_ALL;
18098            if (ver.sdkVersion != mSdkVersion) {
18099                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18100                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18101                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18102            }
18103            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18104
18105            // Yay, everything is now upgraded
18106            ver.forceCurrent();
18107
18108            mSettings.writeLPr();
18109        }
18110
18111        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18112        sendResourcesChangedBroadcast(true, false, loaded, null);
18113    }
18114
18115    private void unloadPrivatePackages(final VolumeInfo vol) {
18116        mHandler.post(new Runnable() {
18117            @Override
18118            public void run() {
18119                unloadPrivatePackagesInner(vol);
18120            }
18121        });
18122    }
18123
18124    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18125        final String volumeUuid = vol.fsUuid;
18126        if (TextUtils.isEmpty(volumeUuid)) {
18127            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18128            return;
18129        }
18130
18131        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18132        synchronized (mInstallLock) {
18133        synchronized (mPackages) {
18134            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18135            for (PackageSetting ps : packages) {
18136                if (ps.pkg == null) continue;
18137
18138                final ApplicationInfo info = ps.pkg.applicationInfo;
18139                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18140                if (deletePackageLI(ps.name, null, false, null,
18141                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
18142                    unloaded.add(info);
18143                } else {
18144                    Slog.w(TAG, "Failed to unload " + ps.codePath);
18145                }
18146            }
18147
18148            mSettings.writeLPr();
18149        }
18150        }
18151
18152        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18153        sendResourcesChangedBroadcast(false, false, unloaded, null);
18154    }
18155
18156    /**
18157     * Examine all users present on given mounted volume, and destroy data
18158     * belonging to users that are no longer valid, or whose user ID has been
18159     * recycled.
18160     */
18161    private void reconcileUsers(String volumeUuid) {
18162        // TODO: also reconcile DE directories
18163        final File[] files = FileUtils
18164                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18165        for (File file : files) {
18166            if (!file.isDirectory()) continue;
18167
18168            final int userId;
18169            final UserInfo info;
18170            try {
18171                userId = Integer.parseInt(file.getName());
18172                info = sUserManager.getUserInfo(userId);
18173            } catch (NumberFormatException e) {
18174                Slog.w(TAG, "Invalid user directory " + file);
18175                continue;
18176            }
18177
18178            boolean destroyUser = false;
18179            if (info == null) {
18180                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18181                        + " because no matching user was found");
18182                destroyUser = true;
18183            } else {
18184                try {
18185                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18186                } catch (IOException e) {
18187                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18188                            + " because we failed to enforce serial number: " + e);
18189                    destroyUser = true;
18190                }
18191            }
18192
18193            if (destroyUser) {
18194                synchronized (mInstallLock) {
18195                    try {
18196                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18197                    } catch (InstallerException e) {
18198                        Slog.w(TAG, "Failed to clean up user dirs", e);
18199                    }
18200                }
18201            }
18202        }
18203    }
18204
18205    private void assertPackageKnown(String volumeUuid, String packageName)
18206            throws PackageManagerException {
18207        synchronized (mPackages) {
18208            final PackageSetting ps = mSettings.mPackages.get(packageName);
18209            if (ps == null) {
18210                throw new PackageManagerException("Package " + packageName + " is unknown");
18211            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18212                throw new PackageManagerException(
18213                        "Package " + packageName + " found on unknown volume " + volumeUuid
18214                                + "; expected volume " + ps.volumeUuid);
18215            }
18216        }
18217    }
18218
18219    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18220            throws PackageManagerException {
18221        synchronized (mPackages) {
18222            final PackageSetting ps = mSettings.mPackages.get(packageName);
18223            if (ps == null) {
18224                throw new PackageManagerException("Package " + packageName + " is unknown");
18225            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18226                throw new PackageManagerException(
18227                        "Package " + packageName + " found on unknown volume " + volumeUuid
18228                                + "; expected volume " + ps.volumeUuid);
18229            } else if (!ps.getInstalled(userId)) {
18230                throw new PackageManagerException(
18231                        "Package " + packageName + " not installed for user " + userId);
18232            }
18233        }
18234    }
18235
18236    /**
18237     * Examine all apps present on given mounted volume, and destroy apps that
18238     * aren't expected, either due to uninstallation or reinstallation on
18239     * another volume.
18240     */
18241    private void reconcileApps(String volumeUuid) {
18242        final File[] files = FileUtils
18243                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18244        for (File file : files) {
18245            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18246                    && !PackageInstallerService.isStageName(file.getName());
18247            if (!isPackage) {
18248                // Ignore entries which are not packages
18249                continue;
18250            }
18251
18252            try {
18253                final PackageLite pkg = PackageParser.parsePackageLite(file,
18254                        PackageParser.PARSE_MUST_BE_APK);
18255                assertPackageKnown(volumeUuid, pkg.packageName);
18256
18257            } catch (PackageParserException | PackageManagerException e) {
18258                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18259                synchronized (mInstallLock) {
18260                    removeCodePathLI(file);
18261                }
18262            }
18263        }
18264    }
18265
18266    /**
18267     * Reconcile all app data for the given user.
18268     * <p>
18269     * Verifies that directories exist and that ownership and labeling is
18270     * correct for all installed apps on all mounted volumes.
18271     */
18272    void reconcileAppsData(int userId, int flags) {
18273        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18274        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18275            final String volumeUuid = vol.getFsUuid();
18276            reconcileAppsData(volumeUuid, userId, flags);
18277        }
18278    }
18279
18280    /**
18281     * Reconcile all app data on given mounted volume.
18282     * <p>
18283     * Destroys app data that isn't expected, either due to uninstallation or
18284     * reinstallation on another volume.
18285     * <p>
18286     * Verifies that directories exist and that ownership and labeling is
18287     * correct for all installed apps.
18288     */
18289    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18290        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18291                + Integer.toHexString(flags));
18292
18293        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18294        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18295
18296        boolean restoreconNeeded = false;
18297
18298        // First look for stale data that doesn't belong, and check if things
18299        // have changed since we did our last restorecon
18300        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18301            if (!isUserKeyUnlocked(userId)) {
18302                throw new RuntimeException(
18303                        "Yikes, someone asked us to reconcile CE storage while " + userId
18304                                + " was still locked; this would have caused massive data loss!");
18305            }
18306
18307            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18308
18309            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18310            for (File file : files) {
18311                final String packageName = file.getName();
18312                try {
18313                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18314                } catch (PackageManagerException e) {
18315                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18316                    synchronized (mInstallLock) {
18317                        destroyAppDataLI(volumeUuid, packageName, userId,
18318                                StorageManager.FLAG_STORAGE_CE);
18319                    }
18320                }
18321            }
18322        }
18323        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18324            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18325
18326            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18327            for (File file : files) {
18328                final String packageName = file.getName();
18329                try {
18330                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18331                } catch (PackageManagerException e) {
18332                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18333                    synchronized (mInstallLock) {
18334                        destroyAppDataLI(volumeUuid, packageName, userId,
18335                                StorageManager.FLAG_STORAGE_DE);
18336                    }
18337                }
18338            }
18339        }
18340
18341        // Ensure that data directories are ready to roll for all packages
18342        // installed for this volume and user
18343        final List<PackageSetting> packages;
18344        synchronized (mPackages) {
18345            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18346        }
18347        int preparedCount = 0;
18348        for (PackageSetting ps : packages) {
18349            final String packageName = ps.name;
18350            if (ps.pkg == null) {
18351                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18352                // TODO: might be due to legacy ASEC apps; we should circle back
18353                // and reconcile again once they're scanned
18354                continue;
18355            }
18356
18357            if (ps.getInstalled(userId)) {
18358                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18359
18360                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18361                    // We may have just shuffled around app data directories, so
18362                    // prepare them one more time
18363                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18364                }
18365
18366                preparedCount++;
18367            }
18368        }
18369
18370        if (restoreconNeeded) {
18371            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18372                SELinuxMMAC.setRestoreconDone(ceDir);
18373            }
18374            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18375                SELinuxMMAC.setRestoreconDone(deDir);
18376            }
18377        }
18378
18379        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18380                + " packages; restoreconNeeded was " + restoreconNeeded);
18381    }
18382
18383    /**
18384     * Prepare app data for the given app just after it was installed or
18385     * upgraded. This method carefully only touches users that it's installed
18386     * for, and it forces a restorecon to handle any seinfo changes.
18387     * <p>
18388     * Verifies that directories exist and that ownership and labeling is
18389     * correct for all installed apps. If there is an ownership mismatch, it
18390     * will try recovering system apps by wiping data; third-party app data is
18391     * left intact.
18392     * <p>
18393     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18394     */
18395    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18396        prepareAppDataAfterInstallInternal(pkg);
18397        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18398        for (int i = 0; i < childCount; i++) {
18399            PackageParser.Package childPackage = pkg.childPackages.get(i);
18400            prepareAppDataAfterInstallInternal(childPackage);
18401        }
18402    }
18403
18404    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18405        final PackageSetting ps;
18406        synchronized (mPackages) {
18407            ps = mSettings.mPackages.get(pkg.packageName);
18408            mSettings.writeKernelMappingLPr(ps);
18409        }
18410
18411        final UserManager um = mContext.getSystemService(UserManager.class);
18412        for (UserInfo user : um.getUsers()) {
18413            final int flags;
18414            if (um.isUserUnlocked(user.id)) {
18415                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18416            } else if (um.isUserRunning(user.id)) {
18417                flags = StorageManager.FLAG_STORAGE_DE;
18418            } else {
18419                continue;
18420            }
18421
18422            if (ps.getInstalled(user.id)) {
18423                // Whenever an app changes, force a restorecon of its data
18424                // TODO: when user data is locked, mark that we're still dirty
18425                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18426            }
18427        }
18428    }
18429
18430    /**
18431     * Prepare app data for the given app.
18432     * <p>
18433     * Verifies that directories exist and that ownership and labeling is
18434     * correct for all installed apps. If there is an ownership mismatch, this
18435     * will try recovering system apps by wiping data; third-party app data is
18436     * left intact.
18437     */
18438    private void prepareAppData(String volumeUuid, int userId, int flags,
18439            PackageParser.Package pkg, boolean restoreconNeeded) {
18440        if (DEBUG_APP_DATA) {
18441            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18442                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18443        }
18444
18445        final String packageName = pkg.packageName;
18446        final ApplicationInfo app = pkg.applicationInfo;
18447        final int appId = UserHandle.getAppId(app.uid);
18448
18449        Preconditions.checkNotNull(app.seinfo);
18450
18451        synchronized (mInstallLock) {
18452            try {
18453                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18454                        appId, app.seinfo, app.targetSdkVersion);
18455            } catch (InstallerException e) {
18456                if (app.isSystemApp()) {
18457                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18458                            + ", but trying to recover: " + e);
18459                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18460                    try {
18461                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18462                                appId, app.seinfo, app.targetSdkVersion);
18463                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18464                    } catch (InstallerException e2) {
18465                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18466                    }
18467                } else {
18468                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18469                }
18470            }
18471
18472            if (restoreconNeeded) {
18473                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18474            }
18475
18476            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18477                // Create a native library symlink only if we have native libraries
18478                // and if the native libraries are 32 bit libraries. We do not provide
18479                // this symlink for 64 bit libraries.
18480                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18481                    final String nativeLibPath = app.nativeLibraryDir;
18482                    try {
18483                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18484                                nativeLibPath, userId);
18485                    } catch (InstallerException e) {
18486                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18487                    }
18488                }
18489            }
18490        }
18491    }
18492
18493    /**
18494     * For system apps on non-FBE devices, this method migrates any existing
18495     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
18496     * requested by the app.
18497     */
18498    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18499        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18500                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
18501            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
18502                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18503            synchronized (mInstallLock) {
18504                try {
18505                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18506                } catch (InstallerException e) {
18507                    logCriticalInfo(Log.WARN,
18508                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18509                }
18510            }
18511            return true;
18512        } else {
18513            return false;
18514        }
18515    }
18516
18517    private void unfreezePackage(String packageName) {
18518        synchronized (mPackages) {
18519            final PackageSetting ps = mSettings.mPackages.get(packageName);
18520            if (ps != null) {
18521                ps.frozen = false;
18522            }
18523        }
18524    }
18525
18526    @Override
18527    public int movePackage(final String packageName, final String volumeUuid) {
18528        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18529
18530        final int moveId = mNextMoveId.getAndIncrement();
18531        mHandler.post(new Runnable() {
18532            @Override
18533            public void run() {
18534                try {
18535                    movePackageInternal(packageName, volumeUuid, moveId);
18536                } catch (PackageManagerException e) {
18537                    Slog.w(TAG, "Failed to move " + packageName, e);
18538                    mMoveCallbacks.notifyStatusChanged(moveId,
18539                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18540                }
18541            }
18542        });
18543        return moveId;
18544    }
18545
18546    private void movePackageInternal(final String packageName, final String volumeUuid,
18547            final int moveId) throws PackageManagerException {
18548        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18549        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18550        final PackageManager pm = mContext.getPackageManager();
18551
18552        final boolean currentAsec;
18553        final String currentVolumeUuid;
18554        final File codeFile;
18555        final String installerPackageName;
18556        final String packageAbiOverride;
18557        final int appId;
18558        final String seinfo;
18559        final String label;
18560        final int targetSdkVersion;
18561
18562        // reader
18563        synchronized (mPackages) {
18564            final PackageParser.Package pkg = mPackages.get(packageName);
18565            final PackageSetting ps = mSettings.mPackages.get(packageName);
18566            if (pkg == null || ps == null) {
18567                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18568            }
18569
18570            if (pkg.applicationInfo.isSystemApp()) {
18571                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18572                        "Cannot move system application");
18573            }
18574
18575            if (pkg.applicationInfo.isExternalAsec()) {
18576                currentAsec = true;
18577                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18578            } else if (pkg.applicationInfo.isForwardLocked()) {
18579                currentAsec = true;
18580                currentVolumeUuid = "forward_locked";
18581            } else {
18582                currentAsec = false;
18583                currentVolumeUuid = ps.volumeUuid;
18584
18585                final File probe = new File(pkg.codePath);
18586                final File probeOat = new File(probe, "oat");
18587                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18588                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18589                            "Move only supported for modern cluster style installs");
18590                }
18591            }
18592
18593            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18594                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18595                        "Package already moved to " + volumeUuid);
18596            }
18597            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18598                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18599                        "Device admin cannot be moved");
18600            }
18601
18602            if (ps.frozen) {
18603                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18604                        "Failed to move already frozen package");
18605            }
18606            ps.frozen = true;
18607
18608            codeFile = new File(pkg.codePath);
18609            installerPackageName = ps.installerPackageName;
18610            packageAbiOverride = ps.cpuAbiOverrideString;
18611            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18612            seinfo = pkg.applicationInfo.seinfo;
18613            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18614            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18615        }
18616
18617        // Now that we're guarded by frozen state, kill app during move
18618        final long token = Binder.clearCallingIdentity();
18619        try {
18620            killApplication(packageName, appId, "move pkg");
18621        } finally {
18622            Binder.restoreCallingIdentity(token);
18623        }
18624
18625        final Bundle extras = new Bundle();
18626        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18627        extras.putString(Intent.EXTRA_TITLE, label);
18628        mMoveCallbacks.notifyCreated(moveId, extras);
18629
18630        int installFlags;
18631        final boolean moveCompleteApp;
18632        final File measurePath;
18633
18634        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18635            installFlags = INSTALL_INTERNAL;
18636            moveCompleteApp = !currentAsec;
18637            measurePath = Environment.getDataAppDirectory(volumeUuid);
18638        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18639            installFlags = INSTALL_EXTERNAL;
18640            moveCompleteApp = false;
18641            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18642        } else {
18643            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18644            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18645                    || !volume.isMountedWritable()) {
18646                unfreezePackage(packageName);
18647                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18648                        "Move location not mounted private volume");
18649            }
18650
18651            Preconditions.checkState(!currentAsec);
18652
18653            installFlags = INSTALL_INTERNAL;
18654            moveCompleteApp = true;
18655            measurePath = Environment.getDataAppDirectory(volumeUuid);
18656        }
18657
18658        final PackageStats stats = new PackageStats(null, -1);
18659        synchronized (mInstaller) {
18660            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18661                unfreezePackage(packageName);
18662                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18663                        "Failed to measure package size");
18664            }
18665        }
18666
18667        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18668                + stats.dataSize);
18669
18670        final long startFreeBytes = measurePath.getFreeSpace();
18671        final long sizeBytes;
18672        if (moveCompleteApp) {
18673            sizeBytes = stats.codeSize + stats.dataSize;
18674        } else {
18675            sizeBytes = stats.codeSize;
18676        }
18677
18678        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18679            unfreezePackage(packageName);
18680            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18681                    "Not enough free space to move");
18682        }
18683
18684        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18685
18686        final CountDownLatch installedLatch = new CountDownLatch(1);
18687        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18688            @Override
18689            public void onUserActionRequired(Intent intent) throws RemoteException {
18690                throw new IllegalStateException();
18691            }
18692
18693            @Override
18694            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18695                    Bundle extras) throws RemoteException {
18696                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18697                        + PackageManager.installStatusToString(returnCode, msg));
18698
18699                installedLatch.countDown();
18700
18701                // Regardless of success or failure of the move operation,
18702                // always unfreeze the package
18703                unfreezePackage(packageName);
18704
18705                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18706                switch (status) {
18707                    case PackageInstaller.STATUS_SUCCESS:
18708                        mMoveCallbacks.notifyStatusChanged(moveId,
18709                                PackageManager.MOVE_SUCCEEDED);
18710                        break;
18711                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18712                        mMoveCallbacks.notifyStatusChanged(moveId,
18713                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18714                        break;
18715                    default:
18716                        mMoveCallbacks.notifyStatusChanged(moveId,
18717                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18718                        break;
18719                }
18720            }
18721        };
18722
18723        final MoveInfo move;
18724        if (moveCompleteApp) {
18725            // Kick off a thread to report progress estimates
18726            new Thread() {
18727                @Override
18728                public void run() {
18729                    while (true) {
18730                        try {
18731                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18732                                break;
18733                            }
18734                        } catch (InterruptedException ignored) {
18735                        }
18736
18737                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18738                        final int progress = 10 + (int) MathUtils.constrain(
18739                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18740                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18741                    }
18742                }
18743            }.start();
18744
18745            final String dataAppName = codeFile.getName();
18746            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18747                    dataAppName, appId, seinfo, targetSdkVersion);
18748        } else {
18749            move = null;
18750        }
18751
18752        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18753
18754        final Message msg = mHandler.obtainMessage(INIT_COPY);
18755        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18756        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18757                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18758                packageAbiOverride, null);
18759        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18760        msg.obj = params;
18761
18762        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18763                System.identityHashCode(msg.obj));
18764        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18765                System.identityHashCode(msg.obj));
18766
18767        mHandler.sendMessage(msg);
18768    }
18769
18770    @Override
18771    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18772        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18773
18774        final int realMoveId = mNextMoveId.getAndIncrement();
18775        final Bundle extras = new Bundle();
18776        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18777        mMoveCallbacks.notifyCreated(realMoveId, extras);
18778
18779        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18780            @Override
18781            public void onCreated(int moveId, Bundle extras) {
18782                // Ignored
18783            }
18784
18785            @Override
18786            public void onStatusChanged(int moveId, int status, long estMillis) {
18787                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18788            }
18789        };
18790
18791        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18792        storage.setPrimaryStorageUuid(volumeUuid, callback);
18793        return realMoveId;
18794    }
18795
18796    @Override
18797    public int getMoveStatus(int moveId) {
18798        mContext.enforceCallingOrSelfPermission(
18799                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18800        return mMoveCallbacks.mLastStatus.get(moveId);
18801    }
18802
18803    @Override
18804    public void registerMoveCallback(IPackageMoveObserver callback) {
18805        mContext.enforceCallingOrSelfPermission(
18806                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18807        mMoveCallbacks.register(callback);
18808    }
18809
18810    @Override
18811    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18812        mContext.enforceCallingOrSelfPermission(
18813                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18814        mMoveCallbacks.unregister(callback);
18815    }
18816
18817    @Override
18818    public boolean setInstallLocation(int loc) {
18819        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18820                null);
18821        if (getInstallLocation() == loc) {
18822            return true;
18823        }
18824        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18825                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18826            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18827                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18828            return true;
18829        }
18830        return false;
18831   }
18832
18833    @Override
18834    public int getInstallLocation() {
18835        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18836                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18837                PackageHelper.APP_INSTALL_AUTO);
18838    }
18839
18840    /** Called by UserManagerService */
18841    void cleanUpUser(UserManagerService userManager, int userHandle) {
18842        synchronized (mPackages) {
18843            mDirtyUsers.remove(userHandle);
18844            mUserNeedsBadging.delete(userHandle);
18845            mSettings.removeUserLPw(userHandle);
18846            mPendingBroadcasts.remove(userHandle);
18847            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18848        }
18849        synchronized (mInstallLock) {
18850            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18851            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18852                final String volumeUuid = vol.getFsUuid();
18853                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18854                try {
18855                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18856                } catch (InstallerException e) {
18857                    Slog.w(TAG, "Failed to remove user data", e);
18858                }
18859            }
18860            synchronized (mPackages) {
18861                removeUnusedPackagesLILPw(userManager, userHandle);
18862            }
18863        }
18864    }
18865
18866    /**
18867     * We're removing userHandle and would like to remove any downloaded packages
18868     * that are no longer in use by any other user.
18869     * @param userHandle the user being removed
18870     */
18871    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18872        final boolean DEBUG_CLEAN_APKS = false;
18873        int [] users = userManager.getUserIds();
18874        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18875        while (psit.hasNext()) {
18876            PackageSetting ps = psit.next();
18877            if (ps.pkg == null) {
18878                continue;
18879            }
18880            final String packageName = ps.pkg.packageName;
18881            // Skip over if system app
18882            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18883                continue;
18884            }
18885            if (DEBUG_CLEAN_APKS) {
18886                Slog.i(TAG, "Checking package " + packageName);
18887            }
18888            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18889            if (keep) {
18890                if (DEBUG_CLEAN_APKS) {
18891                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18892                }
18893            } else {
18894                for (int i = 0; i < users.length; i++) {
18895                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18896                        keep = true;
18897                        if (DEBUG_CLEAN_APKS) {
18898                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18899                                    + users[i]);
18900                        }
18901                        break;
18902                    }
18903                }
18904            }
18905            if (!keep) {
18906                if (DEBUG_CLEAN_APKS) {
18907                    Slog.i(TAG, "  Removing package " + packageName);
18908                }
18909                mHandler.post(new Runnable() {
18910                    public void run() {
18911                        deletePackageX(packageName, userHandle, 0);
18912                    } //end run
18913                });
18914            }
18915        }
18916    }
18917
18918    /** Called by UserManagerService */
18919    void createNewUser(int userHandle) {
18920        synchronized (mInstallLock) {
18921            try {
18922                mInstaller.createUserConfig(userHandle);
18923            } catch (InstallerException e) {
18924                Slog.w(TAG, "Failed to create user config", e);
18925            }
18926            mSettings.createNewUserLI(this, mInstaller, userHandle);
18927        }
18928        synchronized (mPackages) {
18929            applyFactoryDefaultBrowserLPw(userHandle);
18930            primeDomainVerificationsLPw(userHandle);
18931        }
18932    }
18933
18934    void newUserCreated(final int userHandle) {
18935        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18936        // If permission review for legacy apps is required, we represent
18937        // dagerous permissions for such apps as always granted runtime
18938        // permissions to keep per user flag state whether review is needed.
18939        // Hence, if a new user is added we have to propagate dangerous
18940        // permission grants for these legacy apps.
18941        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18942            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18943                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18944        }
18945    }
18946
18947    @Override
18948    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18949        mContext.enforceCallingOrSelfPermission(
18950                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18951                "Only package verification agents can read the verifier device identity");
18952
18953        synchronized (mPackages) {
18954            return mSettings.getVerifierDeviceIdentityLPw();
18955        }
18956    }
18957
18958    @Override
18959    public void setPermissionEnforced(String permission, boolean enforced) {
18960        // TODO: Now that we no longer change GID for storage, this should to away.
18961        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18962                "setPermissionEnforced");
18963        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18964            synchronized (mPackages) {
18965                if (mSettings.mReadExternalStorageEnforced == null
18966                        || mSettings.mReadExternalStorageEnforced != enforced) {
18967                    mSettings.mReadExternalStorageEnforced = enforced;
18968                    mSettings.writeLPr();
18969                }
18970            }
18971            // kill any non-foreground processes so we restart them and
18972            // grant/revoke the GID.
18973            final IActivityManager am = ActivityManagerNative.getDefault();
18974            if (am != null) {
18975                final long token = Binder.clearCallingIdentity();
18976                try {
18977                    am.killProcessesBelowForeground("setPermissionEnforcement");
18978                } catch (RemoteException e) {
18979                } finally {
18980                    Binder.restoreCallingIdentity(token);
18981                }
18982            }
18983        } else {
18984            throw new IllegalArgumentException("No selective enforcement for " + permission);
18985        }
18986    }
18987
18988    @Override
18989    @Deprecated
18990    public boolean isPermissionEnforced(String permission) {
18991        return true;
18992    }
18993
18994    @Override
18995    public boolean isStorageLow() {
18996        final long token = Binder.clearCallingIdentity();
18997        try {
18998            final DeviceStorageMonitorInternal
18999                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19000            if (dsm != null) {
19001                return dsm.isMemoryLow();
19002            } else {
19003                return false;
19004            }
19005        } finally {
19006            Binder.restoreCallingIdentity(token);
19007        }
19008    }
19009
19010    @Override
19011    public IPackageInstaller getPackageInstaller() {
19012        return mInstallerService;
19013    }
19014
19015    private boolean userNeedsBadging(int userId) {
19016        int index = mUserNeedsBadging.indexOfKey(userId);
19017        if (index < 0) {
19018            final UserInfo userInfo;
19019            final long token = Binder.clearCallingIdentity();
19020            try {
19021                userInfo = sUserManager.getUserInfo(userId);
19022            } finally {
19023                Binder.restoreCallingIdentity(token);
19024            }
19025            final boolean b;
19026            if (userInfo != null && userInfo.isManagedProfile()) {
19027                b = true;
19028            } else {
19029                b = false;
19030            }
19031            mUserNeedsBadging.put(userId, b);
19032            return b;
19033        }
19034        return mUserNeedsBadging.valueAt(index);
19035    }
19036
19037    @Override
19038    public KeySet getKeySetByAlias(String packageName, String alias) {
19039        if (packageName == null || alias == null) {
19040            return null;
19041        }
19042        synchronized(mPackages) {
19043            final PackageParser.Package pkg = mPackages.get(packageName);
19044            if (pkg == null) {
19045                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19046                throw new IllegalArgumentException("Unknown package: " + packageName);
19047            }
19048            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19049            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19050        }
19051    }
19052
19053    @Override
19054    public KeySet getSigningKeySet(String packageName) {
19055        if (packageName == null) {
19056            return null;
19057        }
19058        synchronized(mPackages) {
19059            final PackageParser.Package pkg = mPackages.get(packageName);
19060            if (pkg == null) {
19061                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19062                throw new IllegalArgumentException("Unknown package: " + packageName);
19063            }
19064            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19065                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19066                throw new SecurityException("May not access signing KeySet of other apps.");
19067            }
19068            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19069            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19070        }
19071    }
19072
19073    @Override
19074    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19075        if (packageName == null || ks == null) {
19076            return false;
19077        }
19078        synchronized(mPackages) {
19079            final PackageParser.Package pkg = mPackages.get(packageName);
19080            if (pkg == null) {
19081                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19082                throw new IllegalArgumentException("Unknown package: " + packageName);
19083            }
19084            IBinder ksh = ks.getToken();
19085            if (ksh instanceof KeySetHandle) {
19086                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19087                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19088            }
19089            return false;
19090        }
19091    }
19092
19093    @Override
19094    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19095        if (packageName == null || ks == null) {
19096            return false;
19097        }
19098        synchronized(mPackages) {
19099            final PackageParser.Package pkg = mPackages.get(packageName);
19100            if (pkg == null) {
19101                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19102                throw new IllegalArgumentException("Unknown package: " + packageName);
19103            }
19104            IBinder ksh = ks.getToken();
19105            if (ksh instanceof KeySetHandle) {
19106                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19107                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19108            }
19109            return false;
19110        }
19111    }
19112
19113    private void deletePackageIfUnusedLPr(final String packageName) {
19114        PackageSetting ps = mSettings.mPackages.get(packageName);
19115        if (ps == null) {
19116            return;
19117        }
19118        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19119            // TODO Implement atomic delete if package is unused
19120            // It is currently possible that the package will be deleted even if it is installed
19121            // after this method returns.
19122            mHandler.post(new Runnable() {
19123                public void run() {
19124                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19125                }
19126            });
19127        }
19128    }
19129
19130    /**
19131     * Check and throw if the given before/after packages would be considered a
19132     * downgrade.
19133     */
19134    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19135            throws PackageManagerException {
19136        if (after.versionCode < before.mVersionCode) {
19137            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19138                    "Update version code " + after.versionCode + " is older than current "
19139                    + before.mVersionCode);
19140        } else if (after.versionCode == before.mVersionCode) {
19141            if (after.baseRevisionCode < before.baseRevisionCode) {
19142                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19143                        "Update base revision code " + after.baseRevisionCode
19144                        + " is older than current " + before.baseRevisionCode);
19145            }
19146
19147            if (!ArrayUtils.isEmpty(after.splitNames)) {
19148                for (int i = 0; i < after.splitNames.length; i++) {
19149                    final String splitName = after.splitNames[i];
19150                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19151                    if (j != -1) {
19152                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19153                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19154                                    "Update split " + splitName + " revision code "
19155                                    + after.splitRevisionCodes[i] + " is older than current "
19156                                    + before.splitRevisionCodes[j]);
19157                        }
19158                    }
19159                }
19160            }
19161        }
19162    }
19163
19164    private static class MoveCallbacks extends Handler {
19165        private static final int MSG_CREATED = 1;
19166        private static final int MSG_STATUS_CHANGED = 2;
19167
19168        private final RemoteCallbackList<IPackageMoveObserver>
19169                mCallbacks = new RemoteCallbackList<>();
19170
19171        private final SparseIntArray mLastStatus = new SparseIntArray();
19172
19173        public MoveCallbacks(Looper looper) {
19174            super(looper);
19175        }
19176
19177        public void register(IPackageMoveObserver callback) {
19178            mCallbacks.register(callback);
19179        }
19180
19181        public void unregister(IPackageMoveObserver callback) {
19182            mCallbacks.unregister(callback);
19183        }
19184
19185        @Override
19186        public void handleMessage(Message msg) {
19187            final SomeArgs args = (SomeArgs) msg.obj;
19188            final int n = mCallbacks.beginBroadcast();
19189            for (int i = 0; i < n; i++) {
19190                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19191                try {
19192                    invokeCallback(callback, msg.what, args);
19193                } catch (RemoteException ignored) {
19194                }
19195            }
19196            mCallbacks.finishBroadcast();
19197            args.recycle();
19198        }
19199
19200        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19201                throws RemoteException {
19202            switch (what) {
19203                case MSG_CREATED: {
19204                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19205                    break;
19206                }
19207                case MSG_STATUS_CHANGED: {
19208                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19209                    break;
19210                }
19211            }
19212        }
19213
19214        private void notifyCreated(int moveId, Bundle extras) {
19215            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19216
19217            final SomeArgs args = SomeArgs.obtain();
19218            args.argi1 = moveId;
19219            args.arg2 = extras;
19220            obtainMessage(MSG_CREATED, args).sendToTarget();
19221        }
19222
19223        private void notifyStatusChanged(int moveId, int status) {
19224            notifyStatusChanged(moveId, status, -1);
19225        }
19226
19227        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19228            Slog.v(TAG, "Move " + moveId + " status " + status);
19229
19230            final SomeArgs args = SomeArgs.obtain();
19231            args.argi1 = moveId;
19232            args.argi2 = status;
19233            args.arg3 = estMillis;
19234            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19235
19236            synchronized (mLastStatus) {
19237                mLastStatus.put(moveId, status);
19238            }
19239        }
19240    }
19241
19242    private final static class OnPermissionChangeListeners extends Handler {
19243        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19244
19245        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19246                new RemoteCallbackList<>();
19247
19248        public OnPermissionChangeListeners(Looper looper) {
19249            super(looper);
19250        }
19251
19252        @Override
19253        public void handleMessage(Message msg) {
19254            switch (msg.what) {
19255                case MSG_ON_PERMISSIONS_CHANGED: {
19256                    final int uid = msg.arg1;
19257                    handleOnPermissionsChanged(uid);
19258                } break;
19259            }
19260        }
19261
19262        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19263            mPermissionListeners.register(listener);
19264
19265        }
19266
19267        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19268            mPermissionListeners.unregister(listener);
19269        }
19270
19271        public void onPermissionsChanged(int uid) {
19272            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19273                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19274            }
19275        }
19276
19277        private void handleOnPermissionsChanged(int uid) {
19278            final int count = mPermissionListeners.beginBroadcast();
19279            try {
19280                for (int i = 0; i < count; i++) {
19281                    IOnPermissionsChangeListener callback = mPermissionListeners
19282                            .getBroadcastItem(i);
19283                    try {
19284                        callback.onPermissionsChanged(uid);
19285                    } catch (RemoteException e) {
19286                        Log.e(TAG, "Permission listener is dead", e);
19287                    }
19288                }
19289            } finally {
19290                mPermissionListeners.finishBroadcast();
19291            }
19292        }
19293    }
19294
19295    private class PackageManagerInternalImpl extends PackageManagerInternal {
19296        @Override
19297        public void setLocationPackagesProvider(PackagesProvider provider) {
19298            synchronized (mPackages) {
19299                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19300            }
19301        }
19302
19303        @Override
19304        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19305            synchronized (mPackages) {
19306                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19307            }
19308        }
19309
19310        @Override
19311        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19312            synchronized (mPackages) {
19313                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19314            }
19315        }
19316
19317        @Override
19318        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19319            synchronized (mPackages) {
19320                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19321            }
19322        }
19323
19324        @Override
19325        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19326            synchronized (mPackages) {
19327                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19328            }
19329        }
19330
19331        @Override
19332        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19333            synchronized (mPackages) {
19334                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19335            }
19336        }
19337
19338        @Override
19339        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19340            synchronized (mPackages) {
19341                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19342                        packageName, userId);
19343            }
19344        }
19345
19346        @Override
19347        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19348            synchronized (mPackages) {
19349                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19350                        packageName, userId);
19351            }
19352        }
19353
19354        @Override
19355        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19356            synchronized (mPackages) {
19357                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19358                        packageName, userId);
19359            }
19360        }
19361
19362        @Override
19363        public void setKeepUninstalledPackages(final List<String> packageList) {
19364            Preconditions.checkNotNull(packageList);
19365            List<String> removedFromList = null;
19366            synchronized (mPackages) {
19367                if (mKeepUninstalledPackages != null) {
19368                    final int packagesCount = mKeepUninstalledPackages.size();
19369                    for (int i = 0; i < packagesCount; i++) {
19370                        String oldPackage = mKeepUninstalledPackages.get(i);
19371                        if (packageList != null && packageList.contains(oldPackage)) {
19372                            continue;
19373                        }
19374                        if (removedFromList == null) {
19375                            removedFromList = new ArrayList<>();
19376                        }
19377                        removedFromList.add(oldPackage);
19378                    }
19379                }
19380                mKeepUninstalledPackages = new ArrayList<>(packageList);
19381                if (removedFromList != null) {
19382                    final int removedCount = removedFromList.size();
19383                    for (int i = 0; i < removedCount; i++) {
19384                        deletePackageIfUnusedLPr(removedFromList.get(i));
19385                    }
19386                }
19387            }
19388        }
19389
19390        @Override
19391        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19392            synchronized (mPackages) {
19393                // If we do not support permission review, done.
19394                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19395                    return false;
19396                }
19397
19398                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19399                if (packageSetting == null) {
19400                    return false;
19401                }
19402
19403                // Permission review applies only to apps not supporting the new permission model.
19404                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19405                    return false;
19406                }
19407
19408                // Legacy apps have the permission and get user consent on launch.
19409                PermissionsState permissionsState = packageSetting.getPermissionsState();
19410                return permissionsState.isPermissionReviewRequired(userId);
19411            }
19412        }
19413
19414        @Override
19415        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19416            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19417        }
19418
19419        @Override
19420        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19421                int userId) {
19422            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19423        }
19424    }
19425
19426    @Override
19427    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19428        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19429        synchronized (mPackages) {
19430            final long identity = Binder.clearCallingIdentity();
19431            try {
19432                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19433                        packageNames, userId);
19434            } finally {
19435                Binder.restoreCallingIdentity(identity);
19436            }
19437        }
19438    }
19439
19440    private static void enforceSystemOrPhoneCaller(String tag) {
19441        int callingUid = Binder.getCallingUid();
19442        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19443            throw new SecurityException(
19444                    "Cannot call " + tag + " from UID " + callingUid);
19445        }
19446    }
19447
19448    boolean isHistoricalPackageUsageAvailable() {
19449        return mPackageUsage.isHistoricalPackageUsageAvailable();
19450    }
19451
19452    /**
19453     * Return a <b>copy</b> of the collection of packages known to the package manager.
19454     * @return A copy of the values of mPackages.
19455     */
19456    Collection<PackageParser.Package> getPackages() {
19457        synchronized (mPackages) {
19458            return new ArrayList<>(mPackages.values());
19459        }
19460    }
19461}
19462